Comparator和Comparable的使用
发布日期:2021-05-07 05:54:23 浏览次数:30 分类:精选文章

本文共 2121 字,大约阅读时间需要 7 分钟。

根据 中国大学MOOC java核心技术 陈良育 第十章第六节

整理
•对象实现 Comparable 接口(需要修改对象类)
– 实现compareTo 方法
• > 返回1,== 返回0 ,< 返回-1
– Arrays 和 Collections 在进行对象 sort 时,自动调用该方法

• 新建 Comparator (适用于对象类不可更改的情况)

– 实现compare 方法
• > 返回1, == 返回0,< 返回-1
– Comparator 比较器将作为参数提交给工具类的 sort 方法

自己写的对象类可以用Comparable,可以直接修改(如下面的Person);别人发过来jar文件等自己修改不了类的用Comparator(如Person2Comparator)。

import java.util.Arrays;public class Person implements Comparable
{ String name; int age; public String getName() { return name; } public int getAge() { return age; } public Person(String name, int age) { this.name = name; this.age = age; } public int compareTo(Person another) { int i = 0; i = name.compareTo(another.name); // 使用字符串的比较 if (i == 0) { // 如果名字一样,比较年龄, 返回比较年龄结果 return age - another.age; } else { return i; // 名字不一样, 返回比较名字的结果. } } public static void main(String... a) { Person[] ps = new Person[3]; ps[0] = new Person("Tom", 20); ps[1] = new Person("Mike", 18); ps[2] = new Person("Mike", 20); Arrays.sort(ps);//sort升序 for (Person p : ps) { System.out.println(p.getName() + "," + p.getAge()); } }}

Person2假设不可见

public class Person2 {   	private String name;    private int age;	public String getName() {   		return name;	}	public int getAge() {   		return age;	}    public Person2(String name, int age)    {       	this.name = name;    	this.age = age;    }}

需要比较Person2,则用Comparator

import java.util.Arrays;import java.util.Comparator;public class Person2Comparator  implements Comparator
{ public int compare(Person2 one, Person2 another) { int i = 0; i = one.getName().compareTo(another.getName()); if (i == 0) { // 如果名字一样,比较年龄,返回比较年龄结果 return one.getAge() - another.getAge(); } else { return i; // 名字不一样, 返回比较名字的结果. } } public static void main(String[] args) { // TODO Auto-generated method stub Person2[] ps = new Person2[3]; ps[0] = new Person2("Tom", 20); ps[1] = new Person2("Mike", 18); ps[2] = new Person2("Mike", 20); Arrays.sort(ps, new Person2Comparator()); for (Person2 p : ps) { System.out.println(p.getName() + "," + p.getAge()); } }}
上一篇:2020-10-29
下一篇:粘代码出现的错误解决

发表评论

最新留言

能坚持,总会有不一样的收获!
[***.219.124.196]2025年04月19日 09时56分33秒