程序的目的是验证当两个对象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());
    }
 }

解决方案 »

  1.   

    equals一定是和hashCode一起重写的
      

  2.   

    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());
        }
    }Cat[age:10, color:Red]
    Cat[age:10, color:Red]
    true
    82403
    82403
      

  3.   

    相同的对象的hashCode必须一样,不同的对象的hashCode也可以一样,这是java的一个参考的规范。而且你要想让两个对象equals方法返回true,hashCode要相同那么你就必须重写hashCode,默认的情况下,不同的对象的hashCode的值是不会一样的。
    public void hashCode() {
         return String.valueOf(age).hashCode() + color.hashCode();
    }
    这样就可以达到你的目的了。