Java问题。
我想用to String方法打印出一个数组, 但我得到的就是这个:
fifo.Fifo@2a139a55
fifo.Fifo@15db9742
我知道这指向了保存数组的地步, 但是如何使用toStinr方法实际打印出数组?
import java.util.ArrayList;
public class Fifo {
private ArrayList <Object> list;
public Fifo() {
this.list = new ArrayList <Object>();
}
public void push(Object obj) {
list.add(obj);
}
public ArrayList getList() {
return this.list;
}
public Object pull() {
if (list.isEmpty()) {
System.out.println("leer");
return null;
}
Object o = list.get(0);
list.remove(0);
return o;
}
@Override
public boolean equals(Object o) {
if (o == this)
return true;
if (o.getClass() == this.getClass()) {
Fifo other = (Fifo) o;
ArrayList otherList = other.getList();
if (otherList.size() == this.getList().size()) {
boolean sameObjects = true;
for (int i = 0; i < list.size(); i++) {
if (!list.get(i).equals(otherList.get(i))) {
sameObjects = false;
}
}
if (sameObjects)
return true;
}
}
return false;
}
public Fifo clone() {
Fifo cloneObj = new Fifo();
for (int i = 0; i < this.list.size(); i++) {
cloneObj.push(this.list.get(i));
}
return cloneObj;
}
}
这是单独的测试方法:
import java.util.*;
public class Aufgabe {
public static void main(String [] args){
Fifo test = new Fifo();
Fifo test2;
test.push(1234);
test.push("Hallo");
test.push(5678);
test.push("du da");
test.pull();
System.out.println(test.toString());
test2=test.clone();
System.out.println(test2.toString());
System.out.println(test2.equals(test));
}
}
答案 0 :(得分:2)
首先,您没有使用数组,而是使用ArrayList
- 这是Java中List的实现。
其次,您没有打印出数组列表,而是打印包含它的对象 - Foo
的实例。
Fifo test = new Fifo();
// do stuff
System.out.println(test.toString());
如果您只想打印列表,则需要使用
Fifo test = new Fifo();
// do stuff
System.out.println(test.getList());
更好的解决方案是覆盖Foo类中的toString
。
public class Foo {
// everything you already have
public String toString() {
// you can format this however you want
return "Contents of my list: " + list;
}
}
当您将对象传递给System.out.println
时,将自动调用此方法。
Foo test = new Foo();
// do stuff
System.out.println(test);
将导致Contents of my list: [a, b, c]
(其中a, b, c
实际上是您列表中的所有内容。)
补充资料 当您在Java中使用System.out.println时,请记住:
System.out.println(1)
将打印1
,System.out.println(false)
将打印false
。toString()
调用的println
方法。toString
为className@hashCode
。toString
为[LclassName@hashCode
。其他尺寸将在字符串的开头处产生额外的[
。答案 1 :(得分:1)
Java中的数组是不覆盖toString()
方法的对象,因此,正如您所指出的,您将获得包含类名和[default] hashCode()的默认实现。要“正确”将数组转换为字符串,可以使用Arrays.toString
:
MyObject[] array = ...;
System.out.println(Arrays.toString(array));
答案 2 :(得分:0)
使用此:
Arrays.toString(yourArray);
什么toString将打印您的数组将包含哈希码,数组元素的类型,所以不是你真正想要的
答案 3 :(得分:0)
覆盖Object.toString()
并提供可以正常使用的实施方案。
答案 4 :(得分:0)
正如其他人提到的那样使用Arrays.toString()方法。
来到
fifo.Fifo@2a139a55
fifo.Fifo@15db9742
这是Object类中定义的toString()
方法的工作原理。它打印出以下格式的字符串:
ClassName@HexadecimalOfHashCode
这是Object类中定义的默认实现。由于您的FIFO类不会覆盖toString()
方法,因此在FIFO对象上调用toString()
会调用Object类中的toString()
方法。
答案 5 :(得分:0)
您需要覆盖toString()
类中的Fifo
以打印有用的内容。也许这样的事情是合适的:
@Override
public String toString() {
return "Fifo" + list.toString();
}
(这会给你类似Fifo[element1, element2]
。)