关于hashcode()和等于()

关于hashcode()和等于()

问题描述:

我有一个POJO,其中包含hashcode()equals()方法,我已覆盖,但我的查询是,如果我如果我做hashcode()方法评论然后在集合让我说当我在一个哈希映射存储用户定义的对象,那么它会产生什么样的影响......另一件事是,如果我将equals方法作为注释,那么它会产生什么影响如果我尝试输入重复记录,它会将重复记录存储两次!关于hashcode()和等于()

public class Employee { 

String name,job; 
int salary; 

public Employee(String n , String j, int t) 
{ 
    this.name= n; 
    this.job=j; 
    this.salary= t;   
} 

/* @Override 
public int hashCode() { 
    final int prime = 31; 
    int result = 1; 
    result = prime * result + ((job == null) ? 0 : job.hashCode()); 
    result = prime * result + ((name == null) ? 0 : name.hashCode()); 
    result = prime * result + salary; 
    return result; 
}*/ 

/*@Override 
public boolean equals(Object obj) { 
    if (this == obj) 
     return true; 
    if (obj == null) 
     return false; 
    if (getClass() != obj.getClass()) 
     return false; 
    Employee other = (Employee) obj; 
    if (job == null) { 
     if (other.job != null) 
      return false; 
    } else if (!job.equals(other.job)) 
     return false; 
    if (name == null) { 
     if (other.name != null) 
      return false; 
    } else if (!name.equals(other.name)) 
     return false; 
    if (salary != other.salary) 
     return false; 
    return true; 
} 
*/ 

@Override 
public int hashCode() 
    {  
    return name.hashCode()+job.hashCode()+salary;  

} 

@Override 
    public boolean equals(Object obj) { 
    if (this == obj) 
    { 
     return true; 
    } 
    // make sure o can be cast to this class 
    if (obj == null || obj.getClass() != getClass()) 
    { 
     // cannot cast 
     return false; 
    }   

    Employee e = (Employee) obj; 
    return this.name.equals(e.name)&&this.job.equals(e.job)&&this.salary==e.salary; 
} 

@Override 
public String toString() { 
     return name+"\t" +"\t"+ job +"\t"+ salary; 
    } 
} 
+1

您在讨论'equals()'和'hasCode()'方法时**的影响**。您是否没有注意到当您将它们交替注释掉(或可能同时存在)时会发生什么? – Lion 2012-04-15 18:43:46

一旦你评论了一些东西,它不会被编译,也不会对你的程序的其他部分产生任何影响。

此外,并非重写Object.equals()方法意味着equals()只会在两个对象是相同的实例时才返回true。例如:

int[] data = data; //data to create object 
mObject o1 = new mObject(data); //new object from data 
mObject o2 = new mObject(data); //another object from the same data 
System.out.println(o1.equals(o2)); //prints false even though o1 and o2 contain the same information. 

如果你离开了equals,它将使用Object.equals方法,这是true只有两个对象是相同的实例。

。由此,重复对象不会添加,但重复记录可以添加,如果通过不同的对象实例添加相同的数据。

不管你做什么或不做评论,相同的对象(地址明智)不能被添加两次到一个集合。 (对于equals()hashCode()的任何理智的定义)。

当你有两个对象o1o2说,“意思是”同样的事情(有相同的数据):

如果您注释掉hashCode(),你(几乎总是)就可以既增加相同HashSet,即使equals()表示这两个对象是相同的(或作为相同HashMap的键)。这是因为所有基于散列的数据结构首先通过散列码比较对象,然后通过equals()进行比较。

如果你评论equals()没有评论hashCode(),所有集合的行为就好像对象不相等。这是因为即使基于散列的比较在检查hashCode()之后检查equals(),因为即使在适当的实现hashCode()equals()中也可能发生散列冲突。

+0

第一句话极具误导性。引用集合的“相同对象”完全由'hashCode()'和'equals()'定义。虽然这是可笑的,但可以将这些定义为“同一对象”返回不同的值。 – 2012-04-15 19:17:52

+0

编辑清除。 – trutheality 2012-04-15 19:42:31