/** * 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(' '); } }
* 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(' ');
}
}
打印对象就是调用对象本身tostring方法,默认tostring方式是输出地址。某些类重写tostring方法用来输出内容。Arraylist就是重写了tostring方法,所以输出的是Arraylist的内容
1、对于这段代码:
System.out.println(list);
想看他是怎么输出的,点击println看它的源码:
public void print(Object obj) {
write(String.valueOf(obj));
}
发现是按String.valueOf(obj)输出的,继续点进去:
public static String valueOf(Object obj) {
return (obj == null) ? "null" : obj.toString();
}
发现sout是按对象的toString方法输出的,那再去看ArrayList的toString是怎么重写的就好了。
2、ArrayList的toString方法源码:
①找到ArrayList发现它自身没有重写toString方法,而是用的父类AbstractList的父类AbstractCollection的方法
②源码如下: 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(' ');
}
}
你怎么转的,可以把代码粘出来看下。
你要直接打印数组的话直接用Arrays.toString(arr)这个方法