//这是System.out.println的实现,把Object变成string打印出来
public void println(Object x) {
String s = String.valueOf(x);
synchronized (this) {
print(s);
newLine();
}
}
//那String.valueOf干了什么?
public static String valueOf(Object obj) {
return (obj == null) ? "null" : obj.toString();
}
//接下来就是toString了
public String toString() {
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
//hashCode怎么生成?
public native int hashCode();
//好,悲剧了。不过有人留了段注释交代hashcode应该是个什么样子的
/*
The general contract of hashCode is:
只要程序没死,某个object的hashcode不能变,除非equals方法里用到的条件变了。
当然程序挂掉重启的话可以变
Whenever it is invoked on the same object more than once during an execution
of a Java application, the hashCode method must consistently return
the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent
from one execution of an application to another execution of the same
application.
两个object equal的话,hashcode一定相同
If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects
must produce the same integer result.
两个object不equal的话,hashcode倒也不一定不同
不过用在hash table的时候,不同object保证有不同hashcode会提高性能的哦
It is not required that if two objects are unequal according to the
java.lang.Object.equals(java.lang.Object) method, then calling the hashCode method on each of the two objects
must produce distinct integer results.
However, the programmer should be aware
that producing distinct integer results for unequal objects may improve the
performance of hash tables.
As much as is reasonably practical, the hashCode method defined by class
Object does return distinct integers for distinct objects. (This is
typically implemented by converting the internal address of the object into an
integer, but this implementation technique is not required by the JavaTM programming language.)
*/
//虽说Object的hashCode时常和物理地址有关,但难保有些非主流虚拟机不按常理出牌……
//所以看jdk的代码比问百度知道要清楚多了
下面两个问题erliang20088已经专业回答了