简体   繁体   中英

Location of toString() Method of java.util.LinkedList

I am studying LinkedLists and wanted to check Java's implementation.

However, I have some questions.

I saw that I can print the contents of java.util.LinkedList.

Like this:

LinkedList ll = new LinkedList<Integer>();

ll.add(1);
ll.add(2);

System.out.println(ll);

// prints "[1, 2]"

However, I can't find the toString() method of LinkedList.

How does Java do that? How can it trigger the toString() method of every data type it has?

The JavaDoc tells you which method is implement in whch parent class, for example the ones in AbstractCollection

Methods declared in class java.util.AbstractCollection
containsAll, isEmpty, removeAll, retainAll, toString

The way is LinkedList > AbstractSequentialList > AbstractList > AbstractCollection

public class LinkedList<E> extends AbstractSequentialList<E> 
                           implements List<E>, Deque<E>, Cloneable, java.io.Serializable

>> public abstract class AbstractSequentialList<E> extends AbstractList<E> {

>>> public abstract class AbstractList<E> extends AbstractCollection<E> implements List<E> {

You ends up with AbstractCollection.toString that iterates over each item to call their toString and join them with a comma, the whole enclosed in brackets

public String toString() {
    Iterator<E> 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(' ');
    }
}

LinkedList inherits its implementation of toString() from java.util.AbstractCollection , which simply calls toString on the objects in the collection. (All objects have it from Object , so it can just call it.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM