任何時候我嘗試打印一個MyList對象,我得到'User @'一些十六進制數字。 有人可以用打印功能或打印方式幫助我嗎?我聽說試圖覆蓋toString函數,但我似乎無法得到這個工作,我不知道這是否是正確的事情。如何打印MyList的對象?
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);
}
}
你需要實現'toString()'。你知道字符串連接是如何工作的嗎? –
向我們展示您用來打印列表的代碼?你可以實現toString()或只是打印出你想要的用戶的屬性,即user.firstname – rabs