TreeSet的两种排序方法:自然排序和定义比较器,推荐使用定义比较器方法。

<span style="color:#333333;">import java.util.*;
class treeset 
{
	public static void main(String[] args) 
	{
		TreeSet t = new TreeSet();
//		TreeSet t = new TreeSet(new mycomparator());//第二种方法定义
		t.add(new student("a1",18));
		t.add(new student("a2",18));
		t.add(new student("a1",18));
		t.add(new student("a3",16));
		t.add(new student("a4",25));

		for(Iterator it = t.iterator();it.hasNext();)
		{
			student s = (student)it.next();
			sop(s.getName()+","+s.getAge());
		}
	}
	public static void sop(Object obj)
	{
		System.out.println(obj);
	}
}

/*
自然排序法 定义Comparable接口,覆盖CompareTo方法
*/
class student implements Comparable
{
	private String name;
	private int age;
	student(String name,int age)
	{
		this.name = name;
		this.age = age;
	}
	public int compareTo(Object obj)
	{
		if(!(obj instanceof student))
			throw new RuntimeException("不是学生");
		student s = (student)obj;
		if(this.age>s.age)
			return 1;
		if(this.age==s.age)
			return this.name.compareTo(s.name);
		return -1;

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

/*
定义比较器   当两种方法都存在时,以比较器为主。
定义一个类,实现Comparator接口,覆盖compare方法
*/
class mycomparator implements Comparator
{
	public int compare(Object o1,Object o2)
	{
		student s1 = (student)o1;
		student s2 = (student)o2;

		int num = s1.getName().compareTo(s2.getName());
		if(num ==0)
		{
			if(s1.getAge()>s2.getAge())
				return 1;
			if(s1.getAge()==s2.getAge())
				return 0;
			return -1;
		}
		return num;
	}
}</span>


posted on 2015-10-22 22:08  超宇  阅读(319)  评论(0编辑  收藏  举报