`
H_eaven
  • 浏览: 31281 次
  • 性别: Icon_minigender_1
  • 来自: 鲨堡
文章分类
社区版块
存档分类
最新评论

equals和hashCode

阅读更多
  public class Person   
{   
    private int id;   
    private String name;   
    private String password;
	private double salary;
    private int hashCode;   
    public Person(int id,String name,String password,double salary) {   
      this.id = id;   
      this.name = name;   
      this.password = password;   
	  this.salary = salary;
    }   
    public boolean equals(Object obj) {   
       if (this == obj)   
       {   
           return true;   
       }   
       if (!(obj instanceof Person))   
       {   
           return false;   
       }   
       Person other = (Person)obj;   
       if (this.id != other.id)   
       {   
           return false;   
       }   
       if (!nullSafeEquals(this.name,other.name))   
       {   
           return false;   
       }   
       if (!nullSafeEquals(this.password,other.password))   
       {   
           return false;   
       }   
	   if (Double.doubleToLongBits(this.salary) != Double.doubleToLongBits(other.salary))
	   {
           return false;
	   }
       return true;   
    }   
    private boolean nullSafeEquals(Object obj1,Object obj2) {   
        return obj1 == null ? obj2 == null : obj1.equals(obj2);   
    }   

    public int hashCode() {   
       if (hashCode == 0)   
       {   
           int result = 17;   
           result = result * 37 + this.id;   
           result = result * 37 + (this.name == null ? 0 : this.name.hashCode());   
           result = result * 37 + (this.password == null ? 0 : this.password.hashCode());   
		   long temp = Double.doubleToLongBits(this.salary);
		   int salaryInt = (int)(temp ^ (temp >>> 32));
		   result = result * 37 + salaryInt;
           hashCode = result;   
       }   
       return hashCode;   
    }   
    public String toString() {   
       return super.toString() + ": [" + this.name + "]";    
    }   
}  

分享到:
评论
2 楼 H_eaven 2008-10-09  
1.相等的对象要返回相等的哈希码,
2.不相等的对象要返回不相等的哈希码.
违反第一条可能会导致程序的病态,
违反第二条会影响散列效率,对于规模很大的散列表,关系到散列表能否正常工作.
这不是费话,很重要.

当重写了equals方法,相等的条件不再依据默认的引用相等"==",而是变为了自定义的逻辑相等,此时没有重写hashCode方法的话,返回的hashCode还是默认生成值.就违反了1,结果就是相等的对象返回了不相等的哈希码.导致此类无法与所有基于散列值的集合类(HashSet,HashMap,...)在一起正常工作.
1 楼 dayang2001911 2008-10-08  
讲讲hashcode和equals有什么联系?

相关推荐

Global site tag (gtag.js) - Google Analytics