gpt4 book ai didi

java - 如何打印 MyList 的对象?

转载 作者:行者123 更新时间:2023-12-01 23:32:48 25 4
gpt4 key购买 nike

每当我尝试打印 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);
}
}

最佳答案

您声明:

The override I tried went something like this:

@Override
public String toString() {
return String.format(this.head);
}
}

这是一个开始,现在不只是打印头部,而是使用 while 循环迭代整个列表,并创建一个包含所有元素信息的新字符串。然后返回该字符串。

即,

@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;
}
}

请注意,如果您想要 super 高效,您可以使用 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;
}
}

关于java - 如何打印 MyList 的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19085190/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com