Comparable和Comparator的区别
一、概述
Comparable和Comparator都是用来实现比较的,一般用于集合中元素的比较
基本包装类型,Integer、Long以及String都实现了Comparable接口,该接口的排序逻辑必须写在比较对象中,所以又叫自然排序
我们一般集合排序使用的Collections.sort(),默认使用的就是Comparable
public static <T extends Comparable<? super T>> void sort(List<T> list) {
list.sort(null);
}
当然,我们也可以指定比较器,这里使用的就是Comparator了
public static <T> void sort(List<T> list, Comparator<? super T> c) {
list.sort(c);
}
定义了对象Forlan,实现了Comparable接口,重写了compareTo(对象)方法
public class Forlan implements Comparable<Forlan> {
private String name;
/**
* 身高
*/
private int height;
/**
* 体重
*/
private int weight;
public Forlan(String name, int height, int weight) {
this.name = name;
this.height = height;
this.weight = weight;
}
@Override
public String toString() {
return "Forlan{" +
"name='" + name + '\'' +
", height=" + height +
", weight=" + weight +
'}';
}
/**
* 比较身高
*/
@Override
public int compareTo(Forlan forlan) {
return this.height - forlan.height;
}
}
验证比较器
List<Forlan> list = new ArrayList<>();
Forlan forlan1 = new Forlan("身高低,体重中", 170, 130);
Forlan forlan2 = new Forlan("身高高,体重低", 180, 120);
Forlan forlan3 = new Forlan("身高中,体重高", 175, 140);
list.add(forlan1);
list.add(forlan2);
list.add(forlan3);
Collections.sort(list);
System.out.println(list);
// 运行结果
[Forlan{name='身高低,体重中', height=170, weight=130}, Forlan{name='身高中,体重高', height=175, weight=140}, Forlan{name='身高高,体重低', height=180, weight=120}]
定义了对象ForlanW,实现了Comparator接口,重写了compare(T o1, T o2)方法
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class ForlanW implements Comparator<ForlanW>{
private String name;
/**
* 身高
*/
private int height;
/**
* 体重
*/
private int weight;
public ForlanW(String name, int height, int weight) {
this.name = name;
this.height = height;
this.weight = weight;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = weight;
}
@Override
public String toString() {
return "ForlanComparator{" +
"name='" + name + '\'' +
", height=" + height +
", weight=" + weight +
'}';
}
@Override
public int compare(ForlanW o1, ForlanW o2) {
return o1.height - o2.height;
}
public static void main(String[] args) {
List<ForlanW> list = new ArrayList<>();
ForlanW forlan1 = new ForlanW("身高低,体重中", 170, 130);
ForlanW forlan2 = new ForlanW("身高高,体重低", 180, 120);
ForlanW forlan3 = new ForlanW("身高中,体重高", 175, 140);
list.add(forlan1