hashSetコレクションにカスタムオブジェクトを格納


/* 
*            
*                
* Copyright (c) 2011,               
* All rights reserved.   
*     : hashSet                                    
*       :                                  
*     :2012    10    17      
*     :x1.0            
   
*                 
*     :  
*     :  hashSet         
                        ,    
*     :   
*           
*/

import java.util.*;


class Person
{
	private String name;
	private int age;

	public Person(String name, int age)
	{
		this.name = name;
		this.age = age;
	}

	public String getName()
	{
		return this.name;
	}
	public int getAge()
	{
		return this.age;
	}

	public void setName(String name)
	{
		this.name = name;
	}
	public void setName(int age)
	{
		this.age = age;
	}

	public int hashCode()//  hashCode  
	{
		//System.out.println(this.name+"....hashCode");

		return name.hashCode() + age * 39;
	}

	public boolean equals(Object obj)//  equals  
	{
		if(!(obj instanceof Person))
		{
			return false;
		}

		Person p = (Person)obj;

		//System.out.println(this.name+"...equals.."+p.name);

		return this.name.equals(p.name) && this.age == p.age;
	}
}

class HashSetTest2
{
	public static void main(String[] args) 
	{
		HashSet hs = new HashSet();
		hs.add(new Person("lisi01",20));
		hs.add(new Person("lisi02",21));
		hs.add(new Person("lisi04",22));
		hs.add(new Person("lisi03",23));
		hs.add(new Person("lisi02",21));
		hs.add(new Person("lisi04",22));

		//sop("lisi01:" + hs.contains(new Person("lisi01",20)));
		//hs.remove(new Person("lisi01",20));

		for(Iterator it = hs.iterator(); it.hasNext();)
		{
			Person p = (Person) it.next();
			sop("name:" + p.getName() + " :: age:" + p.getAge());
		}

	}

	public static void sop(Object obj)
	{
		System.out.println(obj);
	}
}