日期:2014-05-19  浏览次数:20710 次

我已经重写hashCode方法和equals方法还是不能判断两个重复的对象?
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;
}
}

}

------解决方案--------------------
public boolean equals(Object obj)