toString()方法
在写toString的时候发现了一个小问题。
char [] chars={'a','A','c','5','8'}; int [] ints={1,2,3,4}; System.out.print(chars.toString()); //无法输出数组中的值 System.out.print(ints.toString());
在打印时打印的都是@xxx,不能直接输出里面的值,于是看了眼源码:
/** * Returns a string representation of the object. In general, the * {@code toString} method returns a string that * "textually represents" this object. The result should * be a concise but informative representation that is easy for a * person to read. * It is recommended that all subclasses override this method. * <p> * The {@code toString} method for class {@code Object} * returns a string consisting of the name of the class of which the * object is an instance, the at-sign character `{@code @}', and * the unsigned hexadecimal representation of the hash code of the * object. In other words, this method returns a string equal to the * value of: * getClass().getName() + '@' + Integer.toHexString(hashCode()) * * * @return a string representation of the object. */ public String toString() { return getClass().getName() + "@" + Integer.toHexString(hashCode()); }
这个方法跳到了Object类的toString()方法中,意思是返回的对象的字符串表示形式。Object类的toString方法返回一个字符串,该字符串由对象作为实例的类名(数组也是对象)、@符号字符’ @’和对象哈希码的无符号十六进制表示形式组成。
因此我们最后得到的是@和对象的散列值。
而在需要打印值时,可以用:Arrays.toString()方法。
char [] chars={'a','A','c','5','8'}; int [] ints={1,2,3,4}; System.out.print(Arrays.toString(ints)); System.out.print(Arrays.toString(chars));
Arrays.toString()重写了toString方法,通过StringBuilder使我们拿到了数组中的值,上个源码:
public static String toString(int[] a) { if (a == null) return "null"; int iMax = a.length - 1; if (iMax == -1) return "[]"; StringBuilder b = new StringBuilder(); b.append('['); for (int i = 0; ; i++) { b.append(a[i]); if (i == iMax) return b.append(']').toString(); b.append(", "); }
至于为什么使用StringBuilder,因为这显然是个单线程的过程,所以选择能性能更快的StringBuilder.