1. The sorting method of the Arrays class:
public static void sort(type[] a) //Sort the array in ascending order by default
public static <T> void sort(Type[] a, Comparator<?suprt T > c) //use comparator object to customize sorting
2. Custom sorting rules: Set the comparator object corresponding to the Comparator interface to formulate the comparison rules.
- If it is considered that the data on the left is greater than the data on the right, return a positive integer (return 1);
- If the data on the left is considered to be smaller than the data on the right, return a negative integer (return -1);
- If the data on the left is considered to be equal to the data on the right, return 0;
return 1 | exchange order |
return -1 | do not exchange order |
return 0 | do not exchange order |
3. Case study:
import java.util.Arrays;
import java.util.Comparator;
/**
* Comparator比较对象
*/
public class ArraysDemo {
public static void main(String[] args) {
//1.Arrays的sort方法对于有值特性的数组是默认升序排序
int[] ages = {34,12,42,23};
Arrays.sort(ages);
System.out.println(Arrays.toString(ages));
//2.降序排序(自定义比较器对象,只支持引用类型的排序)
Integer[] ages1 = {34,12,42,23};
/*
参数一:被排序的数组,必须是引用类型的元素
参数二:匿名内部类对象,代表一个比较器对象
*/
Arrays.sort(ages1, new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
// return o1-o2;//默认升序
return o2-o1;//默认降序-(o1-o2)
}
});
System.out.println(Arrays.toString(ages1));
System.out.println("-------------------------------");
Student[] students = new Student[3];
students[0] = new Student("小花",23,157.5);
students[1] = new Student("小星",21,167.5);
students[2] = new Student("小清",20,177.5);
System.out.println(Arrays.toString(students));
//对int型的年龄排序
Arrays.sort(students, new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
return o1.getAge()-o2.getAge();//升序排序
}
});
System.out.println(Arrays.toString(students));
//对double型的身高排序
Arrays.sort(students, new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
return Double.compare(o1.getHeight(), o2.getHeight());
}
});
System.out.println(Arrays.toString(students));
}
}
class Student{
private String name;
private int age;
private double height;
public Student() {
}
public Student(String name, int age, double height) {
this.name = name;
this.age = age;
this.height = height;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public double getHeight() {
return height;
}
public void setHeight(double height) {
this.height = height;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
", height=" + height +
'}';
}
}