/** * Returns the string representation of this {@code Collection}. The presentation * has a specific format. It is enclosed by square brackets ("[]"). Elements * are separated by ', ' (comma and space). * * @return the string representation of this {@code Collection}. */ @Override public String toString() { if (isEmpty()) { return "[]"; } StringBuilder buffer = new StringBuilder(size() * 16); buffer.append('['); Iterator it = iterator(); while (it.hasNext()) { Object next = it.next(); if (next != this) { buffer.append(next); } else { buffer.append("(this Collection)"); } if (it.hasNext()) { buffer.append(", "); } } buffer.append(']'); return buffer.toString(); }
ArrayList > a = new ArrayList<>(); for (int i = 0; i < 2; i++) { ArrayList c = new ArrayList<>(); c.add(i+1); c.add(i+2); c.add(c); //打印单个子集合的字符串形式数据 Log.i("myinfo",c.toString()); } 看日志结果中红色部分,是不是看懂了,如果集合中的子元素是集合本身,就将"(this Collection)" 添加到返回集合中
/** * Returns a string containing a concise, human-readable description of this * object. Subclasses are encouraged to override this method and provide an * implementation that takes into account the object's type and data. The * default implementation is equivalent to the following expression: *
See Writing a useful * {@code toString} method * if you intend implementing your own {@code toString} method. * * @return a printable representation of this object. */ public String toString() { return getClass().getName() + '@' + Integer.toHexString(hashCode()); }
Object d = new Object();Log.i("myinfo",d.toString());05-12 11:23:00.758 17406-17406/com.maiji.magkarepatient I/myinfo: java.lang.Object@e23e786
二、String,StringBuilder,StringBuffer
三个都是字符串的表现形式,但是有区别的
①、String.toString() , 直接返回本身
/** * Returns this string. */ @Override public String toString() { return this; }
②、StringBuilder
官方解释:以字符串的形式 返回这个builder对象的内容
/** * Returns the contents of this builder. * * @return the string representation of the data in this builder. */ @Override public String toString() { /* Note: This method is required to workaround a compiler bug * in the RI javac (at least in 1.5.0_06) that will generate a * reference to the non-public AbstractStringBuilder if we don't * override it here. */ return super.toString(); }
追溯到super.toString()实现
/** * Returns the current String representation. * * @return a String containing the characters in this instance. */ @Override public String toString() { if (count == 0) { return ""; } return StringFactory.newStringFromChars(0, count, value); }
③、StringBuffer
@Override public synchronized String toString() { return super.toString(); }
追溯到super.toString()
/** * Returns the current String representation. * * @return a String containing the characters in this instance. */ @Override public String toString() { if (count == 0) { return ""; } return StringFactory.newStringFromChars(0, count, value); }