简体   繁体   English

接口的两个完全相同的实现给出不同的.hashCode()结果

[英]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.

相关问题 两个不同的Class实例给出相同的hashCode - Two different Class instances giving same hashCode 与两种不同实现的接口 - Interface with two different implementations 为什么this == other和this.hashcode == other.hashcode()给出不同的结果? - Why are this == other and and this.hashcode == other.hashcode() giving different results? GWT-GinModule对不同的实现使用相同的接口 - GWT - GinModule use the same interface for different implementations 具有不同类型的接口的两种实现 - 这不可能吗? - Two implementations for an interface with different types - Is this not possible? 为什么使用相同种子创建的两个Random对象会产生与hashcode()不同的结果 - Why do two Random objects created with the same seed produce different results from hashcode() 两个字符串实例看起来相同,但是它们的哈希码不同 - two string instances seems same, but their hashcode are different 如果 hashcode() 是根据 object 的地址创建 hashcode 的,那么两个内容相同的不同对象如何创建相同的 hashcode? - If the hashcode() creates hashcode based on the address of the object, how can two different objects with same contents create the same hashcode? 在不同的线程上执行两个不同的接口实现 - Have two different Implementations for an interface execute on different thread 为什么具有相同数据的两个不同的 HashSet 具有相同的 HashCode? - Why do two different HashSets with the same data have the same HashCode?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM