I didn't override toString()
so I am confused. Isn't an ArrayList
an object like arrays since they are created using new
?
Example:
ArrayList <String> arri= new ArrayList();
String one="one";
String two=new String ("two");
arri.add(one);
arri.add(two);
System.out.println(arri);
//output:
//[one, two]
Thanks
You don't have to override toString()
... the object you're calling it on does. You're calling toString()
on an ArrayList
, and ArrayList
overrides toString
... or rather, AbstractCollection
does, and ArrayList
inherits the implementation:
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 by
String.valueOf(Object)
.
See more on this question at Stackoverflow