为什么在打印一个
ArrayList
对象时,输出的不是此对象的地址,而是该集合中的值?是如何实现的?
分析:
Object
类是Java
中其他所有类的基类,没有Object
类Java
面向对象无从谈起,所有类都是Object
类的直接子类或间接子类
而在Object
类的toString()
方法中,返回的是 getClass().getName() + "@" + Integer.toHexString(hashCode())
也就是地址值,打印ArrayList
对象没有输出地址值,便可知道ArrayList
重写了toString()
方法.
查看源码:
- 点击
ArrayList
查看源码,发现其中并没有toString()
方法,查看他的父类 - 在父类
AbstractList
中查找,依然没有,在查看上一层父类 - 在
AbstractList
的父类AbstractCollection
查找,果然发现重写了
/**
* 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
* (<tt>"[]"</tt>). Adjacent elements are separated by the characters
* <tt>", "</tt> (comma and space). Elements are converted to strings as
* by {@link String#valueOf(Object)}.
*
* @return a string representation of this collection
*/
public String toString() {
Iterator<E> it = iterator();
if (! it.hasNext())
return "[]";
StringBuilder sb = new StringBuilder();
sb.append('[');
for (;;) {
E e = it.next();
sb.append(e == this ? "(this Collection)" : e);
if (! it.hasNext())
return sb.append(']').toString();
sb.append(',').append(' ');
}
}
doc注释翻译:
返回此集合的字符串表示形式。此字符串由集合的元素列表按顺序组成,他们按他的迭代器返回.
用方括号括起来(“[]”)。相邻的元素由字符分隔(逗号和空格)。元素被转换为字符串,
通过 {@link字符串#返回对象的值(对象)}。
分析源码:
-
使用
Iterator
迭代器判断集合中是否含有元素,没有的话就只返回一对"[]" -
在循环外创建
StringBuilder
对象,先添加左方括号 -
循环集合,添加当前元素到
StringBuilder
对象 -
判断当前元素是否为最后一位,是则添加右方括号,执行
StringBuilder
的toString()
方法并返回,不是则添加一个逗号一位空格,继续下一层循环