在leetcode第一题(链接)中,遇到了一个Array.toString(result)和result.toString的结果不一致的问题,百度之后没有很清晰的认知,只知道结果看似是乱码,但其实是与hashCode或者内存地址有关的或者是有意义的结果。最近在学习java object类的时候学到:所有类直接或间接地继承了Object类,且Object类的方法中toString方法可以被所有类重写,感觉会对理解上述问题有帮助,于是研究了一下object和array的源码,总结如下。
- java.lang.Object
toString():
/**
* 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:
* <blockquote>
* <pre>
* getClass().getName() + '@' + Integer.toHexString(hashCode())
* </pre></blockquote>
*
* @return a string representation of the object.
*/
public String toString() {
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
- java.util.Arrays
toString():
/**
* Returns a string representation of the contents of the specified array.
* The string representation consists of a list of the array's elements,
* enclosed in square brackets (<tt>"[]"</tt>). Adjacent elements are
* separated by the characters <tt>", "</tt> (a comma followed by a
* space). Elements are converted to strings as by
* <tt>String.valueOf(int)</tt>. Returns <tt>"null"</tt> if <tt>a</tt> is
* <tt>null</tt>.
*
* @param a the array whose string representation to return
* @return a string representation of <tt>a</tt>
* @since 1.5
*/
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(", ");
}
}
由上述代码可以得知,arr.toString()方法得到的结果是“类名+@+此对象哈希码的无符号十六进制数”,而Arrays.toString(arr)才是将此数组输出的结果。但是,由代码可以看出此方法输出的数组是有格式的,是"[1,2,3]"类型的,如果想要输出无格式的1 2 3,则需要对该方法进行重写。
3. hashCode
具体更多的hashCode的知识可以自行去了解,这里只简单了解下:Object类的hashCode返回对象的内存地址经过处理后的结构,由于每个对象的内存地址都不一样,所以哈希码也不一样。