本帖最后由 瓶中人 于 2013-10-22 00:37 编辑
class Cat
{
private String name;
private int age;
private double weight;
private Color color;
public Cat(String name , int age , double weight , Color color){
this.name = name;
this.age = age;
this.weight = weight;
this.color = color;
}
public boolean equals(Object obj){
if(this == obj){
return true;
}
if (obj == null)
{
return false;
}
if(this.getClass() != obj.getClass()){
return false;
}
Cat cat = (Cat)obj;
return name.equals(cat.name)&&(age == cat.age)&&(weight == cat.weight)&&(color.equals(cat.color));
}
public int hashCode(){
return 7 * name.hashCode() + 11* new Integer(age).hashCode() + 13 * new Double(weight).hashCode() + 17 * color.hashCode();
}
}
为什么比较对象是否相等要重写hashCode()方法呢,明明有重写equals()就可以说明问题了? |