TreeSetの2番目のソート方法


/* 
*            
*                
* Copyright (c) 2011,               
* All rights reserved.   
*     :TreeSet                                   
*       :                                  
*     :2012    10    20      
*     :x1.0            
   
*                 
*     :  
*     :          ,      。

                 ,  Comparator  ,  compare  
*     :   
*           
*/
import java.util.*;

class TreeSetTest2 
{
	public static void main(String[] args) 
	{
		TreeSet ts = new TreeSet(new MyCompare());
		ts.add(new Person("lisi04",22));
		ts.add(new Person("lisi02",21));
		ts.add(new Person("lisi03",23));
		ts.add(new Person("lisi02",21));
		ts.add(new Person("lisi01",20));
		//ts.add(new Person("lisi04",22));

		for(Iterator it = ts.iterator(); it.hasNext(); )
		{
			Person p = (Person)it.next();
			System.out.println("name:" + p.getName() + " :: age:" + p.getAge());
		}
	}
}

class Person implements Comparable //            
{
	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 compareTo(Object obj)
	{
		if(!(obj instanceof Person))
		{
			throw new RuntimeException("     ");
		}

		Person p = (Person)obj;
		//System.out.println(this.name+"....compareto....."+p.name);
		if(this.age > p.age)
			return 1;
		if(this.age == p.age)
		{
			return this.name.compareTo(p.name);
		}
		return -1;
	}
}

class MyCompare implements Comparator
{
	public int compare(Object o1, Object o2)
	{
		Person p1 = (Person)o1;
		Person p2 = (Person)o2;

		int num = p1.getName().compareTo(p2.getName());

		if(num == 0)
		{
			return new Integer(p1.getAge()).compareTo(new Integer(p2.getAge()));
			/*
			if(s1.getAge()>s2.getAge())
				return 1;
			if(s1.getAge()==s2.getAge())
				return 0;
			return -1;
			*/
		}
		return num;
	}
}