参考链接:
https://www.cnblogs.com/macyzhang/p/9861302.html
https://www.jianshu.com/p/ebf037d54661
- Arrays.sort(T[] a)是对数组元素按字典序进行升序排列
public class Main {
public static void main(String[] args){
Integer[] arr = {5,4,7,9,2,12,54,21,1};
//升序
Arrays.sort(arr);
System.out.println(Arrays.toString(arr));
}
}
output:
[1, 2, 4, 5, 7, 9, 12, 21, 54]
- Arrays.sort(T[] a, Comparator<? Super T> c)用Comparator接口实现自定义排序规则
public class Main {
public static void main(String[] args){
Integer[] arr = {5,4,7,9,2,12,54,21,1};
//降序
Arrays.sort(arr, new Comparator<Integer>() {
public int compare(Integer a, Integer b) {
return b-a;
}
});
System.out.println(Arrays.toString(arr));
}
}
output:
[54, 21, 12, 9, 7, 5, 4, 2, 1]
- Arrays.sort(T[] a, int fromIndex, int toIndex)实现对数组中的一部分进行排序
对数组a中,index属于[fromIndex, toIndex)的元素进行排序
同样,Arrays.sort(T[] a, int fromIndex, int toIndex, Comparator<? Super T> c)可实现自定义排序规则
public class Main {
public static void main(String[] args){
Integer[] arr = {5,4,7,9,2,12,54,21,1};
//局部排序-升序
Arrays.sort(arr, 2, 7);
System.out.println(Arrays.toString(arr));
}
}
output:
[5, 4, 2, 7, 9, 12, 54, 21, 1]
对于自定义规则,我的理解是,如果返回值>0,则交换两个输入的位置。
自定义排序规则的例子:
可以根据重量或大小进行排序。
class Dog{
int size;
int weight;
public Dog(int s, int w){
size = s;
weight = w;
}
}
class DogSizeComparator implements Comparator<Dog>{
@Override
public int compare(Dog o1, Dog o2) {
return o1.size - o2.size;
}
}
class DogWeightComparator implements Comparator<Dog>{
@Override
public int compare(Dog o1, Dog o2) {
return o1.weight - o2.weight;
}
}
public class ArraySort {
public static void main(String[] args) {
Dog d1 = new Dog(2, 50);
Dog d2 = new Dog(1, 30);
Dog d3 = new Dog(3, 40);
Dog[] dogArray = {d1, d2, d3};
printDogs(dogArray);
Arrays.sort(dogArray, new DogSizeComparator());
printDogs(dogArray);
Arrays.sort(dogArray, new DogWeightComparator());
printDogs(dogArray);
}
public static void printDogs(Dog[] dogs){
for(Dog d: dogs)
System.out.print("size="+d.size + " weight=" + d.weight + " ");
System.out.println();
}
}
size=2 weight=50 size=1 weight=30 size=3 weight=40
size=1 weight=30 size=2 weight=50 size=3 weight=40
size=1 weight=30 size=3 weight=40 size=2 weight=50