How to print out all the elements of a List in Java?

user1335361 picture user1335361 · Apr 16, 2012 · Viewed 915.5k times · Source

I am trying to print out all the elements of a List, however it is printing the pointer of the Object rather than the value.

This is my printing code...

for(int i=0;i<list.size();i++){
    System.out.println(list.get(i));
} 

Could anyone please help me why it isn't printing the value of the elements.

Answer

Holly Cummins picture Holly Cummins · Apr 16, 2012

The following is compact and avoids the loop in your example code (and gives you nice commas):

System.out.println(Arrays.toString(list.toArray()));

However, as others have pointed out, if you don't have sensible toString() methods implemented for the objects inside the list, you will get the object pointers (hash codes, in fact) you're observing. This is true whether they're in a list or not.