TreeSet的第二种排序方式

/* 
* 程序头部注释开始   
* 程序的版权和版本声明部分   
* 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;
	}
}

你可能感兴趣的:(String,object,Integer,iterator,Class,任务)