参考资料:Java语言程序设计(进阶篇) ——梁勇先生 著 戴开宇先生 译
- 运行环境
- 一、前言
- 二、概要
- 三、Comparable
- 3.1 通过实现Comparable接口完成学生类的排序
- 3.1.1 按成绩排序
- 3.1.2 按身高排序
- 3.1.3 总结Comparable
- 四、Comparator 比较器
- 4.1 通过Comparator比较器实现排序
- 4.2 编写对象比较大小的方法
- 五、总结
- Windows10
- JDK8
- IDAE
在Java语言中,如果要判断两个变量的大小,也许你首先会想到
if(a > b){
// ...
}
但是,这样有着极大的限制,比如 String类型的两个变量无法直接用 > < 比较
比较大小最多的应用就是数组之间的排序
比如使用 java.uti.Collections 类中静态的sort方法实现数组列表的排序
public static void main(String[] args) {
ArrayList list = new ArrayList(Arrays.asList(4,3,6,8));
Collections.sort(list);
System.out.println(list);
}
运行结果
[3, 4, 6, 8]
众所周知,Java是一门面向对象编程的语言,这意味着我们不只是对上例的Integer类型的数组列表进行排序,也可能是其他类型比如String、Character,或者是别的类,在实际应用中,比如比较一个班级里,所有学生的成绩、身高体重等等。
JDK8提供了 java.lang.Comparable 和 java.util.Comparator这两个接口
专门用于解决两个对象比较的问题,同时它们被应用到了各种原生类里的排序功能。
二、概要在JDK原生API中许多类都实现了 Comparable 接口,比如最基本的引用类型Integer、String、Date等,其中,所有基本类型的数字包装类都实现了这个接口。
Comparable 接口中定义了唯一的方法:compareTo(T o) 用于比较实现 Comparable 接口的 同一个类 的两个元素。
java.util.Comparator
Comparable接口在 java.lang包中,用于实现该接口实现类之间的比较
去掉注释后的 Comparable.java 源码如下:
package java.lang; import java.util.*; public interface Comparable{ public int compareTo(T o); }
compareTo(T o) 方法 返回值的含义:
| 返回值 | 含义 |
|---|---|
| 0 | 当前对象和传入的形参o比较结果相等 |
| 1 | 当前对象比传入的形参o比较结果大 |
| -1 | 当前对象比传入的形参o比较结果小 |
升序,当前对象 < 形参时,返回 -1
降序, 当前对象 < 形参时,返回 1
该接口仅仅声明了一个compareTo方法,这意味着它的实现类必须重写这个方法
其中
比如,声明一个可比较的自定义类Student:
class Student implements Comparable{ private double score; @Override public int compareTo(Student o){ //... } // getScore & setScore }
compareTo()方法实现了当前对象与传入的形参 o 进行比较,比较的逻辑可自定义。
3.1 通过实现Comparable接口完成学生类的排序测试的学生类 Student.java
class Student implements Comparable{ private String name; private double score; private double height; public Student(String name, double score, double height) { this.name = name; this.score =score; this.height=height; } public double getScore(){ return score; } public double getHeight(){ return height; } @Override public int compareTo(Student o) { if(this.score < o.getScore()) return -1; else if(this.score > o.getScore()) return 1; else return 0; } @Override public String toString() { return "Student{" + "name='" + name + ''' + ", score=" + score + ", height=" + height + '}'; } }
Demo.java 测试的主类
class Demo {
public static void main(String[] args) {
ArrayList all = new ArrayList<>();
all.add(new Student("大雄", 0, 140));
all.add(new Student("哆啦A梦",100 ,129));
all.add(new Student("静香",95 ,143));
Collections.sort(all);
for (Student student : all) {
System.out.println(student);
}
}
}
3.1.1 按成绩排序
Student.java 部分修改如下:
升序
@Override
public int compareTo(Student o) {
if(this.score < o.getScore())
return -1;
else if(this.score > o.getScore())
return 1;
else
return 0;
}
降序
@Override
public int compareTo(Student o) {
if(this.score < o.getScore())
return 1;
else if(this.score > o.getScore())
return -1;
else
return 0;
}
测试升序的运行结果
3.1.2 按身高排序Student{name=‘大雄’, score=0.0, height=140.0}
Student{name=‘静香’, score=95.0, height=143.0}
Student{name=‘哆啦A梦’, score=100.0, height=129.0}
升序
@Override
public int compareTo(Student o) {
if(this.height < o.getHeight())
return -1;
else if(this.height > o.getHeight())
return 1;
else
return 0;
}
降序
@Override
public int compareTo(Student o) {
if(this.height < o.getHeight())
return 1;
else if(this.height > o.getHeight())
return -1;
else
return 0;
}
测试升序的运行结果
3.1.3 总结ComparableStudent{name=‘静香’, score=95.0, height=143.0}
Student{name=‘大雄’, score=0.0, height=140.0}
Student{name=‘哆啦A梦’, score=100.0, height=129.0}
综上,使用该接口只需要重写compareTo(T o) 方法,并且方法返回-1、0、1三种结果,在方法中比较的是当前对象和形参对象的大小。
四、Comparator 比较器Comparator接口在java.util包中,用于比较未实现java.lang.comparable接口类
比较器接口中实现了 java.io.Serializable 接口,用于标志类是可序列化的。
该接口的源码如下:
package java.util; import java.io.Serializable; import java.util.function.Function; import java.util.function.ToIntFunction; import java.util.function.ToLongFunction; import java.util.function.ToDoubleFunction; import java.util.Comparators; public interface Comparator{//...}
Comparator 接口的所有方法
在下图中除了带箭头的方法,其他方法均在接口里实现了。
由此可见,Comparator接口的实现类同样需要重写compare()方法。
不过不同于Comparable接口里的compare()方法的是,前者需要传入两个参数,后者只需传入一个参数。
4.1 通过Comparator比较器实现排序与之前不同的是,该接口是由另一个类来实现而不能是要比较的类。
Student 学生实体类
class Student{
private String name;
private double score;
private double height;
public Student(String name, double score, double height) {
this.name = name;
this.score =score;
this.height=height;
}
public double getScore(){
return score;
}
public double getHeight(){
return height;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + ''' +
", score=" + score +
", height=" + height +
'}';
}
}
scoreComparator 专门用于Student对象的成绩比较器类
class scoreComparator implements Comparator{ @Override public int compare(Student o1, Student o2) { if(o1.getScore() > o2.getScore()) return 1; else if(o1.getScore() < o2.getScore()) return -1; else return 0; } }
Demo.java 实现排序的主类
class Demo {
public static void main(String[] args) {
ArrayList all = new ArrayList<>();
all.add(new Student("大雄", 0, 140));
all.add(new Student("哆啦A梦",100 ,129));
all.add(new Student("静香",95 ,143));
all.sort(new scoreComparator());
System.out.println(all);
}
}
运行结果:
4.2 编写对象比较大小的方法[Student{name=‘大雄’, score=0.0, height=140.0}, Student{name=‘静香’, score=95.0, height=143.0}, Student{name=‘哆啦A梦’, score=100.0, height=129.0}]
有了scoreComaprator比较器对象后,可以很轻松的比较学生类的成绩,实现如下:
public Student max(Student o1, Student o2, scoreComparator c){
if(c.compare(o1, o2) > 0)
return o1;
else
return o2;
}
与之前的 Comparable 接口相比
很明显,要想以不同的逻辑,比如身高或者成绩等来比较学生,就需要不同的比较器。
前者是在学生类里重写了comparaTo方法,比较只能通过该方法里面的逻辑
后者则可以定义出更多Comparator接口的实现类,用来表示不同的比较参考对象
五、总结- j a v a . l a n g . C o m p a r a b l e java.lang.Comparable java.lang.Comparable 用于比较 C o m p a r a b l e Comparable Comparable的类的对象
使用 C o m p a r a b l e Comparable Comparable接口比较元素称为使用 自然排序 进行比较
- j a v a . u t i l . C o m p a r a t o r java.util.Comparator java.util.Comparator 用于比较没有实现 C o m p a r a b l e Comparable Comparable 的类的对象
使用 C o m p a r a t o r Comparator Comparator接口比较被称为使用比较器 进行比较
| C o m p a r a b l e Comparable Comparable | C o m p r a t o r Comprator Comprator |
|---|---|
| 实现类即比较的类 | 实现类为其他任意的类 |
| compareTo()方法在比较类中 | compare()方法可放在任意的类 |
| 仅声明compareTo方法 | 提供许多比较的方法 |



