使用 toString 打印出 ArrayList [英] Printing out ArrayList with toString
问题描述
当我创建一个 ArrayList 对象并向其中添加其他对象时,打印出 ArrayList 对象将打印出内部对象的内存引用.但是,如果我将 String 添加到 ArrayList 对象,它不会打印出 String 的内存引用,而是打印出实际的 String 值.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
code> extends) 在其每个元素上使用 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)
转换为字符串.
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
只是获取对象的 toString
值:http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#valueOf(java.lang.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)
如果参数为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屋!