I have created a class Test
storing class Pair
objects in linkedlist data structure defined in the library . To print the Pair
class objects I have overridden method in pair class and it works as shown below -
import java.util.LinkedList;
class Test{
static LinkedList<Pair> list=new LinkedList<Pair>();
public static void main(String[] args){
list.add(new Pair(31,78));
list.add(new Pair(89,67));
list.add(new Pair(90,43));
System.out.println(list);
}
}
class Pair{
int x;
int y;
Pair(int m, int n){
x=m;
y=n;
}
@Override
public String toString(){
return "{ "+ this.x + ", " +this.y+" }";
}
}
The output -
[{ 2, 4 }, { 6, 3 }, { 12, 6 }]
My doubt is regarding the toString()
method-
- What happens internally when I print a Linked List ?
- If I would have stored some integers in a linked list, would Integer class toString() method would have been called?
The implementation of LinkedList<E>.toString()
is inherited from AbstractCollection<E>
; it's documented like this:
Returns a string representation of this collection. The string representation consists of a list of the collection's elements in the order they are returned by its iterator, enclosed in square brackets ("[]"). Adjacent elements are separated by the characters
", "
(comma and space). Elements are converted to strings as byString.valueOf(Object)
.
So String.valueOf
is called on each element - which in turn will call Object.toString()
for any non-null element. In your case, you've overridden that in Pair
, so that's what's called.
If you add some logging in Pair.toString
, like this:
public String toString(){
String ret = "{ "+ this.x + ", " +this.y+" }";
System.out.println("toString called: returning " + ret;
return ret;
}
... you can see it being called (or you could use a debugger). And yes, if the list contained integers, the list's string representation would be "[1, 2, 3, 4, 5]" or whatever. (It's possible that String.valueOf
is optimized to handle numeric types directly, but logically it would call the toString()
override in Integer
.)