[英]Two exact same implementations of an interface are giving different .hashCode() results
I've an interface like this- 我有一个像这样的界面
public interface myInterface {
String getMyString();
}
And two implementations like this- 还有两个这样的实现-
class test implements myInterface {
@Override
public String getMyString() {
return "1,2";
}
}
class test2 implements myInterface {
@Override
public String getMyString() {
return "1,2";
}
}
When I create new instnaces of these two clasess and do .hashCode I get different values for hashCode. 当我创建这两个类的新实例并执行.hashCode时,我会得到不同的hashCode值。 Why so?
为什么这样?
test test = new test();
test2 test2 = new test2();
System.out.println(test.hashCode());
System.out.println(test2.hashCode());
如果三个注释没有提示您问题所在,则您有不同的类,您没有重写hashCode
方法,而是实际上使用接口的方法使您的类具有相同的哈希码。
因为它们是两个不同的对象,所以如果要使它们相同,则需要覆盖哈希码方法。
Quoted from JavaDoc of Object#hashCode()
引用自JavaDoc的
Object#hashCode()
As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects.
在合理可行的范围内,由Object类定义的hashCode方法确实为不同的对象返回不同的整数。 (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.)
(通常通过将对象的内部地址转换为整数来实现,但是JavaTM编程语言不需要此实现技术。)
Unless you have overridden hashCode()
, what described above will be the default behavior. 除非您覆盖了
hashCode()
,否则上面描述的将是默认行为。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.