您的位置:首页 > 移动开发 > Objective-C

向HashSet集合存入对象,去除重复元素(覆写equals和hashCode方法)

2012-04-28 19:40 656 查看
import java.util.*;
class Person
{
private String name;
private int age;
Person(String name,int age)
{
this.age=age;
this.name=name;
}
public int getAge()
{
return age;
}
public String getName()
{
return name;
}
public boolean equals(Object obj)
{
if (!(obj instanceof Person))
{
return false;
}
Person p=(Person)obj;
return this.name.equals(p.name)&&this.age==p.age;
}
public int hashCode()
{
return this.name.hashCode()+age*39;
}
}
class Compare
{
public HashSet com(HashSet h)
{
HashSet h1=new HashSet();
Iterator t=h.iterator();
while (t.hasNext())
{
Object obj=t.next();
if (!h1.contains(obj))
{
h1.add(obj);
}
}
return h1;
}
}
class HashSetTest
{
public static void main(String[] args)
{
HashSet h=new HashSet();
h.add(new Person("xxc1",10));
h.add(new Person("xxc2",20));
h.add(new Person("xxc3",30));
h.add(new Person("xxc4",40));
h.add(new Person("xxc3",30));
Compare c=new Compare();
h=c.com(h);
Iterator t=h.iterator();
while (t.hasNext())
{
Object obj=t.next();
Person p=(Person)obj;
System.out.println(p.getName()+"========="+p.getAge());
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息