首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > J2EE开发 >

小弟我已经重写hashCode方法和equals方法还是不能判断两个重复的对象

2012-08-10 
我已经重写hashCode方法和equals方法还是不能判断两个重复的对象?package testimport java.util.HashSet

我已经重写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)

热点排行