每当我尝试打印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);
}
}
答案 0 :(得分:2)
你说:
我试过的覆盖是这样的:
@Override
public String toString() {
return String.format(this.head);
}
}
这是一个开始,现在不是只打印头,而是使用while循环遍历整个列表,并创建一个包含所有元素信息的新String。然后返回那个String。
即,
@Override
public String toString() {
ListElement tail = this.tail;
// or you might need to start at the head element depending on which way
// you will iterate.
String returnString = "";
// use a while loop here to go through your list
// and add pertinent info from each element to the returnString
return returnString;
}
}
请注意,如果您想要超级高效,那么您将使用StringBuilder进行连接,但是对于您的应用程序,这可能是过度杀戮而不是必需的。
注2:希望ListElement有一个toString()
方法,如果是这样,请在while循环中使用它来获取每个元素的信息。
下一次迭代:
@Override
public String toString() {
String returnString = "";
ListElement currentElement = this.tail;
while (currentElement != null) {
returnString += // *** get toString() info from currentElement
currentElement = // **** reset currentElement to next element
}
return returnString;
}
}
答案 1 :(得分:1)
默认的toString()
方法打印对象的内存地址(您看到的十六进制数字)。
如果你想要不同的东西,你需要:
@Override
public String toString()
{
//do stuff to build a string that describes your object
//return that string you just built
}
答案 2 :(得分:0)
此代码是toString方法的未经测试的实现。尝试一下。
@Override
public String toString()
{
String myString = "";
ListElement currentElement = head;
while (currentElement.next != null)
{
if (myString.length > 0)
{
myString += ",";
}
myString += currentElement.value.toString();
currentElement = currentElement.next;
}
return myString;
}