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?
Thank you very much
CodePudding user response:
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.)
CodePudding user response:
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(' ');
}
}