Treeset类的排序问题

Treeset有两种排序方法(自然排序和比较器排序),使用哪种取决于使用的构造方法。主要讨论存储自定义类时怎么实现排序。

构造方法摘要
TreeSet()
          构造一个新的空 set,该 set 根据其元素的自然顺序进行排序。
TreeSet(Collection<? extendsE> c)
          构造一个包含指定 collection 元素的新 TreeSet,它按照其元素的自然顺序进行排序。
TreeSet(Comparator<? superE> comparator)
          构造一个新的空 TreeSet,它根据指定比较器进行排序。
TreeSet(SortedSet<E> s)
          构造一个与指定有序 set 具有相同映射关系和相同排序的新 TreeSet。

1、自然排序

如果要实现自然排序,自定义类要实现Comparable接口,重写compareTo()方法。代码如下:

public class Student implements Comparable<Student> {
	private String name;
	private int age;

	public Student() {
		super();
	} 

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

	public String getName() {
		return name;
	}

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

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	@Override
	public int compareTo(Student s) {
		// 按照年龄排序,主要条件
		int num = this.age - s.age;
		// 次要条件
		int num2 = num == 0 ? this.name.compareTo(s.name) : num;
		return num2;
	}
}
如果有三个条件
public int compareTo(Student s) {
		// 主要条件 姓名的长度
		int num = this.name.length() - s.name.length();
		// 姓名的长度相同,不代表姓名的内容相同
		int num2 = num == 0 ? this.name.compareTo(s.name) : num;
		// 姓名的长度和内容相同,不代表年龄相同,所以还得继续判断年龄
		int num3 = num2 == 0 ? this.age - s.age : num2;
		return num3;
	}
}

2、比较器

实现比较器排序有两种方式:

方式一

public class ThisComparator implements Comparator<Student> {

	@Override
	public int compare(Student s1, Student s2) {
		// 姓名长度
		int num = s1.getName().length() - s2.getName().length();
		// 姓名内容
		int num2 = num == 0 ? s1.getName().compareTo(s2.getName()) : num;
		// 年龄
		int num3 = num2 == 0 ? s1.getAge() - s2.getAge() : num2;
		return num3;
	}

}
使用的构造方法是这样
TreeSet<Student> ts = new TreeSet<Student>(new <span style="font-family: Arial, Helvetica, sans-serif;">ThisComparator</span><span style="font-family: Arial, Helvetica, sans-serif;"><Student>);</span>

方式二是使用匿名内部类

TreeSet<Student> ts = new TreeSet<Student>(new Comparator<Student>() {
			@Override
			public int compare(Student s1, Student s2) {
				// 姓名长度
				int num = s1.getName().length() - s2.getName().length();
				// 姓名内容
				int num2 = num == 0 ? s1.getName().compareTo(s2.getName())
						: num;
				// 年龄
				int num3 = num2 == 0 ? s1.getAge() - s2.getAge() : num2;
				return num3;
			}
		});






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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值