TreeSet 排序

1.通过构造方法TreeSet(Comparator<? super E> comparator)指定比较器进行排序:

1.1.构造装入 TreeSet 的 bean

public class Foo {

	private int num;

	public int getNum() {
		return num;
	}

	public void setNum(int num) {
		this.num = num;
	}

	public String toString() {
		return "foo:" + this.getNum() + ",";
	}
}

1.2.实现自己的比较器

public class MyComparator implements Comparator<Foo> {

	public int compare(Foo f1, Foo f2) {

		if (f1.getNum() > f2.getNum()) {
			return 1;
		} else if (f1.getNum() == f2.getNum()) {
			return 0;
		} else {
			return -1;
		}
	}
}

1.3.new TreeSet时指定比较器

TreeSet<Foo> set = new TreeSet(new MyComparator());

至此:就可以实现 TreeSet 的排序功能了。


2.通过对需要添加到 TreeSet  的【元素】实现比较器接口进行排序。

2.1.对要添加到 TreeSet 中的元素实现 Comparable 接口

public class Foo implements Comparable {

	private int num;

	public int getNum() {
		return num;
	}

	public void setNum(int num) {
		this.num = num;
	}

	public String toString() {
		return "foo:" + this.getNum() + ",";
	}

	public int compareTo(Object obj) {
		if (obj instanceof Foo) {
			Foo foo = (Foo) obj;
			if (this.num > foo.getNum()) {
				return 1;
			} else if (this.num == foo.getNum()) {
				return 0;
			} else {
				return -1;
			}

		}
		return 0;
	}
}

2.2.创建 TreeSet 直接使用构造方法。

TreeSet<Foo> set = new TreeSet();

至此:就可以实现 TreeSet 的排序功能了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值