程序的目的是验证当两个对象equals为true时,他们的hashcode也一样,可是我的程序老是不通过。。
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;
}
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());
}
}
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());
}
}Cat[age:10, color:Red]
Cat[age:10, color:Red]
true
82403
82403
public void hashCode() {
return String.valueOf(age).hashCode() + color.hashCode();
}
这样就可以达到你的目的了。