System.identityHashCode()为不同的对象提供相同的值

时间:2016-08-19 07:36:30

标签: java hashcode

我有一个employee2 java文件,我创建了3个对象,我正在尝试使用 System.identityhashCode(Object o)计算这些对象的hashcode(),但它总是给出所有对象的值相同,可能如何

注 - >我没有实现hashcode()或equals,我只是使用hashcode()的默认实现

代码如下:

  public class employee2
  {
   private int empid;
   private String name;
   private String dept;

   employee2(){ 

   }

  public employee2(int empid,String name,String dept){
   this.empid=empid;
   this.name=name;
   this.dept=dept;
   }

  public static void main(String args[]){
        employee2 e1=new employee2(9846,"Amol Sngh","Science");
        employee2 e2=new employee2(9844,"Amol Singh","Scienc");
        employee2 e3=new employee2(98446,"Amol Singh","Science");
        employee2 e4=new employee2(96,"Amol Sh","Sciece");

       System.out.println(System.identityHashCode(e1)+"  "+System.identityHashCode(e2)+" "+System.identityHashCode(e3)+"  "+System.identityHashCode(e4));

   }     
 } 

它始终为每个对象提供值 366712642

1 个答案:

答案 0 :(得分:-2)

这就是我所期待的。它总是会为您提供父对象的hashCode,而不是单个实例:

http://www.javaworld.com/article/2073618/java-s-system-identityhashcode.html