import java.util.*;
/*
往HashSet 集合中存入自定义对象
姓名和年龄相同为同一个人,重复元素
*/
class HashSetTest
{
public static void sop(Object obj)
{
System.out.println(obj);
}
public static void main(String[] args)
{
HashSet hs = new HashSet();
hs.add(new PersonHash("a1",11));
hs.add(new PersonHash("a2",21));
hs.add(new PersonHash("a3",31));
hs.add(new PersonHash("a3",31));
Iterator it = hs.iterator();
while(it.hasNext())
{
PersonHash p = (PersonHash)it.next();
sop(p.getName()+"::"+p.getAge());
//sop(p.hashCode());
}
}
}
class PersonHash {
private String name;
private int age;
PersonHash(String name , int age)
{
this.name = name;
this.age = age;
}
public int hashCode()
{
System.out.println(name.hashCode()+age);
return name.hashCode()+age;
//return 60;
}
public boolean equals(Object obj)
{
if(!(obj instanceof PersonHash))
return false;
PersonHash p = (PersonHash)obj;
//用字符串equals方法判断姓名和年龄是否相同
System.out.println(this.name.equals(p.name) && this.age==p.age);
return this.name.equals(p.name) && this.age==p.age;
}
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
}
|
|