When I create an ArrayList object and add other objects to it, printing out the ArrayList object will print out the memory references of the objects inside. However, if I add String to the ArrayList object, it will not print out the memory references of the String but rather the actual String value. String is also an object of a class right, so why does it not print out the String memory reference?
3 Answers
The toString method for a Collection in Java (which is what an ArrayList extends) uses String.valueOf on each of its elements: http://docs.oracle.com/javase/7/docs/api/java/util/AbstractCollection.html#toString()
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).
String.valueOf is simply grabbing the toString value of the object: http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#valueOf(java.lang.Object)
if the argument is
null, then a string equal to "null"; otherwise, the value ofobj.toString()is returned.
Comments
When you print a List, the List's toString() method is called, which in turn calls to toString() method of its elements.
The Object, which every class extends, class has a toString() method that creates the "memory address" output you're seeing (actually it's not the memory address, but anyway). The String class overrides the toString() method to return its contents.
To fix the output "problem", override the toString() method in you classes of the other objects you're adding to your List to return something "human readable".
Comments
toString() method of Object class is overridden by Class AbstractCollection. ArrayList extends AbstractList and AbstractList extends AbstractCollection. Method detail is mentioned below.
public String toString() 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).
Overrides: toString in class Object
Returns: a string representation of this collection
StringoverridesObject.toString. The other objects do notStringimplementtoString()method, as your own classes can. And number which what you see calling "native"Object#toString()- is not memory reference of object, but its hash code.String#toString