引言
今天面试官问我,来说一下你对集合排序的了解,心里一凉,思考许久弱弱的来了一句我只用过Arrays.sort()方法。然后晚上我就抓紧开始研究学习Java集合排序的使用以及原理。
概述
Java中的集合排序包括数组排序都离不开两个接口:Comparable与Comparator接口,下面我们来一一说明。
Comparable接口简介
Comparable接口是排序接口,也就是说如果一个类实现了Comparable接口,就说明该类支持排序。而在一些有序集合如TreeMap作为key值以及TreeSet中不需要指定比较器。该接口只有一个方法:compareTo(T o)
public interface Comparable<T> {
// x.compareTo(y)如果为正值代表x > y,如果为负值代表x < y,如果为0代表x == y
public int compareTo(T o);
}
Comparator接口简介
Comparator接口是比较器接口。如果一个类本身不支持排序,但我们需要控制某个类的次序,我们就可以使用Comparator接口来实现一个该类的比较器。该类除去各种公用方法外需要显示实现的方法只有一个compare(T o1, To2)
public interface Comparator<T> {
// 类似于Comparable接口中的compareTo方法,compare(x, y)如果为正值代表x > y,如果为负值代表x < y,如果为0代表x == y
int compare(T o1, T o2);
}
代码实现
public class CollectionCompare {
public static void main(String[] args) {
List<Goods> list = new ArrayList<>();
list.add(new Goods(10, 10));
list.add(new Goods(5, 11));
list.add(new Goods(7, 12));
list.add(new Goods(16, 15));
list.add(new Goods(12, 5));
list.add(new Goods(13, 19));
list.add(new Goods(3, 6));
list.add(new Goods(9, 18));
list.add(new Goods(22, 11));
System.out.println("未排序前的顺序:" + list);
Collections.sort(list);// Goods实现了Comparable接口
System.out.println("按照单价排序之后的顺序:" + list);
list.sort((o1, o2) -> o2.getValue() - o1.getValue());// lambol表达式实现Comparator接口
System.out.println("按照价值排序之后的顺序:" + list);
}
}
public class Goods implements Comparable<Goods>{
// 货物重量
private int weight;
// 货物价值
private int value;
// 货物单价
private double price;
public Goods(int weight, int value) {
this.weight = weight;
this.value = value;
this.price = (double) value / weight;
}
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = weight;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
@Override
public int compareTo(Goods goods) {
if (goods.price > price) return 1;
if (goods.price < price) return -1;
return 0;
}
@Override
public String toString() {
return "货物重" + weight + "价值为" + value + "单价为" + new BigDecimal(price, new MathContext(3));// 保留3位有效数字
}
}
未排序前的顺序:[
货物重10价值为10单价为1,
货物重5价值为11单价为2.20,
货物重7价值为12单价为1.71,
货物重16价值为15单价为0.938,
货物重12价值为5单价为0.417,
货物重13价值为19单价为1.46,
货物重3价值为6单价为2,
货物重9价值为18单价为2,
货物重22价值为11单价为0.5
]
按照单价排序之后的顺序:[
货物重5价值为11单价为2.20,
货物重3价值为6单价为2,
货物重9价值为18单价为2,
货物重7价值为12单价为1.71,
货物重13价值为19单价为1.46,
货物重10价值为10单价为1,
货物重16价值为15单价为0.938,
货物重22价值为11单价为0.5,
货物重12价值为5单价为0.417
]
按照价值排序之后的顺序:[
货物重13价值为19单价为1.46,
货物重9价值为18单价为2,
货物重16价值为15单价为0.938,
货物重7价值为12单价为1.71,
货物重5价值为11单价为2.20,
货物重22价值为11单价为0.5,
货物重10价值为10单价为1,
货物重3价值为6单价为2,
货物重12价值为5单价为0.417
]
Java集合/数组排序原理
在Java中对集合/数组进行排序常用的方式如下:
- Arrays.sort(T[] t);// T必须可排序或者为基本数据类型
- Arrays.sort(T[] t, Comparator<? super T> c);// 新建比较器
- list.sort(Comparator<? super E> c);// 新建比较器
- Collections.sort(List list);// T必须可排序
- Collections.sort(List list, Comparator<? super T> c);// 新建比较器
我们查看Collections.sort()方法发现它调用的还是list.sort()方法
public class Collections {
public static <T extends Comparable<? super T>> void sort(List<T> list) {// 可排序的T
list.sort(null);
}
public static <T> void sort(List<T> list, Comparator<? super T> c) {// 传入比较器
list.sort(c);
}
}
所以我们去看一看list.sort()方法,发现最终回到了Arrays.sort()方法上
default void sort(Comparator<? super E> c) {
Object[] a = this.toArray();
Arrays.sort(a, (Comparator) c);
ListIterator<E> i = this.listIterator();
for (Object e : a) {
i.next();
i.set((E) e);
}
}
最后我们看一看Arrays.sort()方法
public static <T> void sort(T[] a, Comparator<? super T> c) {
if (c == null) { // 没有比较器,T可排序
sort(a);
} else {
if (LegacyMergeSort.userRequested) //这是兼容1.6之前旧版本,采用的是冒泡排序和归并排序
legacyMergeSort(a, c);
else
TimSort.sort(a, 0, a.length, c, null, 0, 0);
}
}
public static void sort(Object[] a) {
if (LegacyMergeSort.userRequested) //这是兼容1.6之前旧版本,采用的是冒泡排序和归并排序
legacyMergeSort(a);
else
ComparableTimSort.sort(a, 0, a.length, null, 0, 0);
}
private static <T> void legacyMergeSort(T[] a, Comparator<? super T> c) {
//定义心的数组,作为排序后的对象
T[] aux = a.clone();
if (c==null) // 没有比较器,T可排序
mergeSort(aux, a, 0, a.length, 0);
else
mergeSort(aux, a, 0, a.length, 0, c);
}
private static void mergeSort(Object[] src,
Object[] dest,
int low,
int high,
int off) {
int length = high - low;
// 数组大小如果小于7,则使用插入排序
if (length < INSERTIONSORT_THRESHOLD) {
for (int i=low; i<high; i++)
for (int j=i; j>low &&
((Comparable) dest[j-1]).compareTo(dest[j])>0; j--)
swap(dest, j, j-1);
return;
}
// 利用分治思想,进行拆分,递归调用插入排序
int destLow = low;
int destHigh = high;
low += off;
high += off;
int mid = (low + high) >>> 1;
mergeSort(dest, src, low, mid, -off);
mergeSort(dest, src, mid, high, -off);
// 合并相邻两个已排好的部分,若左边最大的 小于 右边最小的,
// 说明数组已经排好顺序,直接拷贝
if (((Comparable)src[mid-1]).compareTo(src[mid]) <= 0) {
System.arraycopy(src, low, dest, destLow, length);
return;
}
// 进行归并排序,
for(int i = destLow, p = low, q = mid; i < destHigh; i++) {
if (q >= high || p < mid && ((Comparable)src[p]).compareTo(src[q])<=0)
dest[i] = src[p++];
else
dest[i] = src[q++];
}
}
// 交换两个元素
private static void swap(Object[] x, int a, int b) {
Object t = x[a];
x[a] = x[b];
x[b] = t;
}