Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
369 views
Welcome To Ask or Share your Answers For Others

1 Answer

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 of obj.toString() is returned.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...