[英]Why System.out.println prints the elements of an arraylist and not the hashcode of the object?
I didn't override toString()
so I am confused. 我没有重写
toString()
所以很困惑。 Isn't an ArrayList
an object like arrays since they are created using new
? ArrayList
不是像数组这样的对象,因为它们是使用new
创建的?
Example: 例:
ArrayList <String> arri= new ArrayList();
String one="one";
String two=new String ("two");
arri.add(one);
arri.add(two);
System.out.println(arri);
//output:
//[one, two]
Thanks 谢谢
You don't have to override toString()
... the object you're calling it on does. 您不必重写
toString()
...调用它的对象确实可以。 You're calling toString()
on an ArrayList
, and ArrayList
overrides toString
... or rather, AbstractCollection
does , and ArrayList
inherits the implementation: 您在
ArrayList
上调用toString()
,并且ArrayList
覆盖toString
...或更确切地说, AbstractCollection
操作 ,而ArrayList
继承了实现:
Returns a string representation of this collection.
返回此集合的字符串表示形式。 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(Object)
转换为字符串。
ArrayList
(与数组不同)覆盖toString()
而String
覆盖toString()
,因此打印ArrayList<String>
会显示该List
所有String
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.