TreeSet的两种排序方法

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>


转载于:https://www.cnblogs.com/chaoyu/p/6436985.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值