package test;import java.util.HashSet;public class HashCodeTest { /**
 * @param args
 */
public static void main(String[] args) {

HashSet<Student> hs1=new HashSet<Student>();hs1.add(new Student(20, "xx"));//根据我经重写的hashCode方法和equals方法new Student(20, "xx")对象和
hs1.add(new Student(30, "xx"));//new Student(30, "xx")对象应该是一样的。
System.out.println(hs1.size()); }}
class Student{
int age;
String name;

public Student(int age,String name){
this.age=age;
this.name=name;
}
   public int hashCode(){
return name.hashCode();
}
public boolean equals(Student stu){
if(this.hashCode()==stu.hashCode()){
return true;
}else{
return false;
}
}

}

解决方案 »

  1.   

    public boolean equals(Object obj)
      

  2.   

    hashCode,equals不是这么写的吧再说eclipse可以自动生成的,别费劲写了属性多了容易错
      

  3.   

    是这样的,我给你试了,你确实是重写了hashcode和equals方法,但你的写法有问题,应该这样写HashSet<Student> hs1=new HashSet<Student>();
    Student a=new Student(20, "xx");
    Student b=new Student(30, "xx");
    hs1.add(a);//根据我经重写的hashCode方法和equals方法new Student(20, "xx")对象和
    hs1.add(b);//new Student(30, "xx")对象应该是一样的。
    System.out.println(hs1.size());
    if(hs1.add(b)){
    System.out.println("zheng");

    }else{
    System.out.println("cuo");
    }
    }
    这样打印出来的就是cuo了,而且即使没有加入成功,打印的长度都是2
      

  4.   

    原因在这里,如果你再加入hashset时再new一个对象的话,系统会认为是一个新的对象,即你的那个对象是Object类型的,也就是说Object obj=new Student(20,"xx");所以你加入第二个时就会被判为是两个不同的对象,Student a=new Student(20, "xx");
    Student b=new Student(30, "xx");如果这样写的话,则都为Student对象,自然就能根据你的重写方法判断两个对象是否为一个对象
      

  5.   

    不能把equals(Object obj)中的Object改成具体的类吗?比如Student类