class Point {
private int xPos, yPos;
public Point(int x, int y) {
xPos = x;
yPos = y;
}
public static void main(String[] args) {
System.out.println(new Point(10,20));
}
}
上述代码的输出返回对象哈希码的相同 ClassName@hex 版本,尽管我引用的文本(S G Ganesh 和 Tushar Sharma 的 OCPJP 指南)指出“每个实例的十六进制值都不同”。难道是我理解不正确吗?
最佳答案
对于 hashCode
#JavaDoc
说
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...
这里你谈论的是ClassName@hex
,它在程序执行期间将保持不变,但是如果你一次又一次地运行程序,你可能会得到这个表示每次不同或几次相同的表示它取决于哈希码并受内存分配的影响。
关于Java:ToString() 每次打印相同的哈希码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27717328/