【发布时间】:2015-05-29 17:48:32
【问题描述】:
class A{
int a;
A(){
this.a = 100;
}
}
//in main, we have:
A a = new A(), b = new A();
//and
String str0 = "123", str1 = "123";
为什么str0和str1的hash码一样,而a和b不一样?
【问题讨论】:
-
str0 和 str1 指向 StringPool 中的相同引用,而 'a' 和 'b' 指向内存中的不同引用,因为使用了 'new' 关键字。
-
与String interning无关。
-
@Crazyjavahacking 确实如此。即使
String没有 覆盖hashCode,OP 也会得到相同的结果,因为str1和str2是对同一个对象的引用,而a和b不是。 -
你在混合概念。如果对象相等,hashCode() 必须返回相同的值,就是这样。实习在这里无关紧要,因为无论如何对象都是平等的。
-
@pbabcdef 但它确实覆盖了
hashCode,,这使得实习变得无关紧要。
标签: java dictionary hash hashmap