Printing out ArrayList with toString

匆匆过客 提交于 2020-01-21 17:35:55

问题


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?


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/29462033/printing-out-arraylist-with-tostring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!