使用toString打印出ArrayList [英] Printing out ArrayList with toString
问题描述
当我创建一个ArrayList对象并向其添加其他对象时,打印出ArrayList对象将打印出内部对象的内存引用.但是,如果我将String添加到ArrayList对象,它将不会打印出String的内存引用,而是打印出实际的String值.字符串也是类权限的对象,那么为什么不打印出字符串内存引用呢?
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?
推荐答案
Java中Collection
的toString
方法(这是ArrayList
扩展的内容)在其每个元素上使用String.valueOf
: http://docs.oracle.com/javase/7/docs/api/java/util/AbstractCollection.html#toString()
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()
字符串表示形式由集合的元素的列表组成,这些元素按其迭代器返回的顺序排列,并括在方括号("[]")中.相邻元素由字符,"(逗号和空格)分隔.元素由
String.valueOf(Object)
转换为字符串.
String.valueOf
只是获取对象的toString
值:
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)
如果参数为
null
,则字符串等于"null";否则,将返回obj.toString()
的值.
if the argument is
null
, then a string equal to "null"; otherwise, the value ofobj.toString()
is returned.
这篇关于使用toString打印出ArrayList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!