Java 中 linkedList 类的没有按照Object类toString 方法输出
ringa_lee
ringa_lee 2017-04-17 17:15:22
0
3
476

Java 中 linkedList 类的 toString() 没什么输出的是一个 return getClass().getName() + "@" + Integer.toHexString(hashCode());,我在它的继承中也没有找到 toString 类的重写

ringa_lee
ringa_lee

ringa_lee

reply all (3)
洪涛

What you are talking about is the default implementation of the Object class

public String toString() { return getClass().getName() + "@" + Integer.toHexString(hashCode()); }

Actually, the output of LinkedList’s toString() is like this

[111, 222, 333]

Why is this? Please look at the picture below:

From the picture, you can see that there is anAbstractCollection
in its ancestor class, and in this class, there is an override oftoString():

public String toString() { Iterator it = iterator(); if (! it.hasNext()) return "[]"; StringBuilder sb = new StringBuilder(); sb.append('['); for (;;) { E e = it.next(); sb.append(e == this ? "(this Collection)" : e); if (! it.hasNext()) return sb.append(']').toString(); sb.append(',').append(' '); } }

Seeing this, you should understand, right?

    PHPzhong
    LinkedList l = new LinkedList(); l.add("hello world"); System.out.println(l.toString()); // 输出[hello world]

    Why is mine different from yours...your code? JRE version?

      迷茫

      java is designed like this, maybe you thinkLinkedListtoString应该把所有Object打印出来,但java设计者就认为只打印LinkedListthe short message itself is fine.

      You can write a function yourself to implement this function. It’s very simple, just loop it.

      LinkedList list; // some code for (MyObject obj: list) { System.out.println(obj); }
        Latest Downloads
        More>
        Web Effects
        Website Source Code
        Website Materials
        Front End Template
        About us Disclaimer Sitemap
        php.cn:Public welfare online PHP training,Help PHP learners grow quickly!