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;
}
}
}
* @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;
}
}
}
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
Student b=new Student(30, "xx");如果这样写的话,则都为Student对象,自然就能根据你的重写方法判断两个对象是否为一个对象