每当我尝试打印 MyList 对象时,我都会得到 'User@' 一些十六进制数字。有人可以用打印功能或主要打印方式帮助我吗?我听说过尝试覆盖 toString 函数,但我似乎无法让它工作,并且不确定这是否是正确的做法。
public class MyList {
private ListElement head, tail; //Forward declaration
void add(Object value) {
if (tail != null) {
tail.next = new ListElement(value);
tail = tail.next;
}
else {
head = tail = new ListElement(value);
}
}
Object remove()
{
assert head != null; // don't remove on empty list
Object result = head.value;
head = head.next;
if (head == null) { //was that the last?
tail = null;
}
return result;
}
//Nested class needed only in the implementation of MyList
private class ListElement {
ListElement(Object value) {this.value = value;}
Object value;
ListElement next; //defaults to null as desired
}
public static void main(String[] args) {
myList anInstance = new myList();
String someValue = "A list element";
anInstance.add(someValue);
String anotherValue = "Another value";
anInstance.add(anotherValue);
}
}
我尝试的覆盖是这样的:
@Override
public String toString() {
return String.format(this.head);
}
}