1. 程式人生 > >向HashSet集合存入物件,去除重複元素(覆寫equals和hashCode方法)

向HashSet集合存入物件,去除重複元素(覆寫equals和hashCode方法)

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());
		}
	}
}