0

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

3 回答 3

2

你说:

我尝试的覆盖是这样的:

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

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

IE,

@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;
  }
}
于 2013-09-30T01:27:56.473 回答
1

默认toString()方法打印对象的内存地址(您看到的那个十六进制数)。

如果你想要不同的东西,你需要:

@Override
public String toString() 
{
    //do stuff to build a string that describes your object
    //return that string you just built
}
于 2013-09-30T01:25:29.930 回答
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;
}
于 2013-09-30T13:38:20.313 回答