Printing out ArrayList with toString

2020-04-12 09:56发布

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?

2条回答
够拽才男人
2楼-- · 2020-04-12 10:34

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.

查看更多
一纸荒年 Trace。
3楼-- · 2020-04-12 10:35

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".

查看更多
登录 后发表回答