日期:2014-05-20 浏览次数:21327 次
class Cat{
int age;
String color;
public Cat();
public Cat(int age,String color){
this.age=age;
this.color=color;
}
public boolean equals(Object obj){
if(obj instanceof Cat)
Cat cat=(Cat) obj;
else return false;
if((Cat.color.equals(this.color))&&(Cat.age==this.age)) return true;
else return false;
}
}
public class TestHash{
public static void main(String args[]){
Cat cat1=new Cat(10,"Red");
Cat cat2=new Cat(10,"Red");
System.out.println(cat1.equals(cat2));
System.out.println(cat1.hashCode());
System.out.println(cat2.hashCode());
}
}
class Cat {
int age;
String color;
public Cat() {}
public Cat(int age,String color) {
this.age=age;
this.color=color;
}
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if(!(obj instanceof Cat))
return false;
Cat cat=(Cat) obj;
if((cat.color.equals(this.color)) && (cat.age==this.age))
return true;
return false;
}
@Override
public int hashCode() {
return 37 * age + color.hashCode();
}
@Override
public String toString() {
return String.format("Cat[age:%d, color:%s]",age,color);
}
}
public class TestHash {
public static void main(String args[]){
Cat cat1=new Cat(10,"Red");
Cat cat2=new Cat(10,"Red");
System.out.println(cat1);
System.out.println(cat2);
System.out.println(cat1.equals(cat2));
System.out.println(cat1.hashCode());
System.out.println(cat2.hashCode());
}
}
------解决方案--------------------
相同的对象的hashCode必须一样,不同的对象的hashCode也可以一样,这是java的一个参考的规范。而且你要想让两个对象equals方法返回true,hashCode要相同那么你就必须重写hashCode,默认的情况下,不同的对象的hashCode的值是不会一样的。
public void hashCode() {
return String.valueOf(age).hashCode() + color.hashCode();
}