Comparator 与Comparable的不同用法

一、Comparable

 Comparable 是在集合内部定义的方法实现的排序,即对象本身实现该接口()。

(1)如String、Integer等基本类型都已实现该接口

List<String> list = new ArrayList<>();
		list.add("c");
		list.add("e");
		list.add("d");
		list.add("b");
		list.add("a");
		System.err.println(list.toString());
		Collections.sort(list);
		System.err.println(list.toString());
		输出结果是:
		[c, e, d, b, a]
		[a, b, c, d, e]
其他的基本类型或者已实现 Comparable接口的对象也是如此。
(2) 对实现该接口的对象list排序时会按照你实现的规则排序。

public class CompareTest {

	public static void main(String[] args) {
		List<Person> list = new ArrayList<>();
		list.add(new Person(3, "c"));
		list.add(new Person(1, "a"));
		list.add(new Person(4, "d"));
		list.add(new Person(2, "b"));
		list.add(new Person(6, "f"));
		list.add(new Person(5, "e"));
		for (Person p : list)
			System.err.println(p.name + "====" + p.id);
		Collections.sort(list);
		System.err.println("排序之后--------------------------");
		for (Person p : list)
			System.err.println(p.name + "====" + p.id);
		输出结果:
		c====3
		a====1
		d====4
		b====2
		f====6
		e====5
		排序之后--------------------------
		a====1
		b====2
		c====3
		d====4
		e====5
		f====6

	}

}

class Person implements Comparable<Person> {
	int id;
	String name;

	public Person(int i, String n) {
		this.id = i;
		this.name = n;
	}

	@Override
	public int compareTo(Person p) {
		return this.id - p.id;
	}
}

   小结:我们不仅使用的Collections.sort()排序时与该接口有关系,其实在使用TreeMap或者TreeSet时按照这种规则进行排序的,当然你也可以定义一个 Comparator接口。

二、Comparator

Comparator 是在集合外部实现的排序。

public class CompareTest {

	public static void main(String[] args) {
		Map<Person, String> map = new TreeMap<>(new Comparator<Person>() {
			@Override
			public int compare(Person o1, Person o2) {
				return o1.id - o2.id;
			}
		});
		map.put(new Person(6, "f"), "f");
		map.put(new Person(4, "d"), "d");
		map.put(new Person(1, "a"), "a");
		map.put(new Person(3, "c"), "c");
		map.put(new Person(2, "b"), "b");
		map.put(new Person(5, "e"), "e");
		for (Entry<Person, String> entry : map.entrySet()) {
			System.err.println(entry.getValue() + "=======" + entry.getKey().id);
		}
	}

}

class Person {
	int id;
	String name;

	public Person(int i, String n) {
		this.id = i;
		this.name = n;
	}

comparator接口的用法也不仅仅这么简单,尤其是map的排序时会有很多用法,请参考: http://blog.csdn.net/lili429/article/details/51104485

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值