Comparator与Comparable

###如何区分Comparable和Comparator

able结尾是形容词,是具有(比较)特性的
tor结尾是名词,是(比较)
如果一个类实现了Comparable,那么它就具有了排序的特性
或者可以外部实现一个比较器Comparator来进行排序。
如果不能修改某个类的源码,就可以利用Comparator接口来在外面对它进行排序,并且该实现可以复用.
:Comparator优先级高于Comparable

###Comparable 简介

Comparable 是排序接口。

若一个类实现了Comparable接口,就意味着“该类支持排序”。 即然实现Comparable接口的类支持排序,假设现在存在“实现Comparable接口的类的对象的List列表(或数组)”,则该List列表(或数组)可以通过 Collections.sort(或 Arrays.sort)进行排序。

此外,“实现Comparable接口的类的对象”可以用作“有序映射(如TreeMap)”中的键或“有序集合(TreeSet)”中的元素,而不需要指定比较器。
###Comparator 简介
Comparator 是比较器接口。

我们若需要控制某个类的次序,而该类本身不支持排序(即没有实现Comparable接口);那么,我们可以建立一个“该类的比较器”来进行排序。这个“比较器”只需要实现Comparator接口即可。

也就是说,我们可以通过“实现Comparator类来新建一个比较器”,然后通过该比较器对类进行排序。
###举例
我想对我自己定义的对象User根据UserId进行排序

public class User {
	private Integer UserId;
	private String UserName;
	public User(Integer UserId,String UserName){
		this.UserId = UserId;
		this.UserName = UserName;
	}
	//getter and setter
	...
}

有下面两种做法
1、外部实现Comparator接口

class MyComparator implements Comparator<User>{
    @Override
    public int compare(User user1, User user2) {
    	int thisVal = user1.getUserId();
		int anotherVal = user2.getUserId();
		return (thisVal<anotherVal ? -1 : (thisVal==anotherVal ? 0 : 1));
    }
}
public class TestMain{
	public static void main(String[] args) {
		Map<User,String> testmap = new TreeMap<User,String>(new MyComparator()); 
		testmap.put(new User(3, "a"), "a");
		testmap.put(new User(1, "a"), "a");
		testmap.put(new User(5, "a"), "a");
		testmap.put(new User(2, "a"), "a");
		for(Entry<User, String> entry : testmap.entrySet()) {
			System.out.println(entry.getKey().getUserId());
		}
	}
}

2、User内部实现Comparable接口

public class User implements Comparable<User>{
	private Integer UserId;
	private String UserName;
	public User(Integer UserId,String UserName){
		this.UserId = UserId;
		this.UserName = UserName;
	}
	//getter and setter
	...
	@Override
	public int compareTo(User user) {
		// TODO Auto-generated method stub
		int thisVal = this.UserId;
		int anotherVal = user.UserId;
		return (thisVal<anotherVal ? -1 : (thisVal==anotherVal ? 0 : 1));
	}
}
public class TestMain{
	public static void main(String[] args) {
		Map<User,String> testmap = new TreeMap<User,String>(); 
		testmap.put(new User(3, "a"), "a");
		testmap.put(new User(1, "a"), "a");
		testmap.put(new User(5, "a"), "a");
		testmap.put(new User(2, "a"), "a");
		for(Entry<User, String> entry : testmap.entrySet()) {
			System.out.println(entry.getKey().getUserId());
		}
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值