Java中Comparable和Comparator接口的区别

Comparable 简介

Comparable 是排序接口

若一个类实现了Comparable接口,就意味着“该类支持排序”。此外,“实现Comparable接口的类的对象”可以用作“有序映射(如TreeMap)”中的键或“有序集合(TreeSet)”中的元素,而不需要指定比较器。
接口中通过x.compareTo(y)来比较x和y的大小。若返回负数,意味着x比y小;返回零,意味着x等于y;返回正数,意味着x大于y。

Comparator 是比较器接口

我们若需要控制某个类的次序,而该类本身不支持排序(即没有实现Comparable接口);那么,我们可以建立一个“该类的比较器”来进行排序。这个“比较器”只需要实现Comparator接口即可。也就是说,我们可以通过“实现Comparator类来新建一个比较器”,然后通过该比较器对类进行排序。
int compare(T o1, T o2)和上面的x.compareTo(y)类似,定义排序规则后返回正数,零和负数分别代表大于,等于和小于。

两者的联系
Comparable相当于“内部比较器”,而Comparator相当于“外部比较器”

代码实现

package mytest;

import java.util.*;

/**
 * @                           _ooOoo_
 *                            o8888888o
 *                            88" . "88
 *                            (| -_- |)
 *                            O\  =  /O
 *                         ____/`---'\____
 *                       .'  \\|     |//  `.
 *                      /  \\|||  :  |||//  \
 *                     /  _||||| -:- |||||-  \
 *                     |   | \\\  -  /// |   |
 *                     | \_|  ''\---/''  |   |
 *                     \  .-\__  `-`  ___/-. /
 *                   ___`. .'  /--.--\  `. . __
 *                ."" '<  `.___\_<|>_/___.'  >'"".
 *               | | :  `- \`.;`\ _ /`;.`/ - ` : | |
 *               \  \ `-.   \_ __\ /__ _/   .-` /  /
 *          ======`-.____`-.___\_____/___.-`____.-'======
 *                             `=---='
 *          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 *                     佛祖保佑        永无BUG
 */

public class LearnCompare
{
	public static void main(String[] args)
	{
		List<Node> list = new ArrayList<Node>();
		list.add(new Node("yguo", 25));
		list.add(new Node("msdfj", 22));
		list.add(new Node("skf", 20));
		list.add(new Node("sfe", 23));
		System.out.println("===Age排序外部比较器===");
		Collections.sort(list, new Comparator<Node>()
		{
			@Override
			public int compare(Node o1, Node o2)
			{
				return o1.getAge() - o2.getAge();
			}
		});

		for (Iterator<Node> it = list.iterator(); it.hasNext(); )
		{
			System.out.println(it.next());
		}
		System.out.println("===Name排序外部比较器====");
		Collections.sort(list, new Comparator<Node>()
		{
			@Override
			public int compare(Node o1, Node o2)
			{
				return o1.getName().compareTo(o2.getName());
			}
		});
		for (Iterator<Node> it = list.iterator(); it.hasNext(); )
		{
			System.out.println(it.next());
		}
		System.out.println("===Age排序 内部比较器===");
		Collections.sort(list);
		for (Iterator<Node> it = list.iterator(); it.hasNext(); )
		{
			System.out.println(it.next());
		}

	}
}

//
class Node implements Comparable<Node>
{
	private String name;
	private int age;

	public Node(String name, int age)
	{
		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(Node other)
	{
		if (age > other.getAge())
			return -1;
		if (age < other.getAge())
			return 1;
		return 0;
	}

	@Override
	public String toString()
	{
		return "Name " + name + " age " + age;
	}
}

参考:
https://blog.csdn.net/u010859650/article/details/85009595
https://blog.csdn.net/yguoelect/article/details/77435073

posted @ 2019-11-22 11:10  sowhat1412  阅读(343)  评论(0)    收藏  举报