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?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
The
toString
method for aCollection
in Java (which is what anArrayList
extends) usesString.valueOf
on each of its elements: http://docs.oracle.com/javase/7/docs/api/java/util/AbstractCollection.html#toString()String.valueOf
is simply grabbing thetoString
value of the object: http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#valueOf(java.lang.Object)When you print a List, the List's
toString()
method is called, which in turn calls totoString()
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). TheString
class overrides thetoString()
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".