一、自然排序
自然排序:类实现了java.lang.Comparable接口,重写compareTo()的规则
如果当前对象this大于形参对象obj,则返回正整数;如果当前对象this小于形参对象obj,则返回负整数;如果当前对象this等于参数对象obj,则返回零。
1.Person类
public class Person implements Comparable<Person> {
private Integer age;
public Person(Integer age) {
this.age = age;
}
@Override
public int compareTo(Person person) {
return this.age - person.age;
}
@Override
public String toString() {
return "Person{" +
"age=" + age +
'}';
}
}
2.测试
Arrays有方法public static void sort(Object[] a)
@Test
public void test1() {
Person[] peoples = new Person[4];
peoples[0] = new Person(11);
peoples[1] = new Person(19);
peoples[2] = new Person(18);
peoples[3] = new Person(10);
Arrays.sort(peoples);
System.out.println(Arrays.toString(peoples));
}
3.结果
二、定制排序
定制排序:java.util.Comparator
当元素的类型没有实现java.lang.Comparable接口而又不方便修改代码时,那么可以考虑使用Comparator的对象来排序
1.Person类
public class Person {
private Integer age;
public Person(Integer age) {
this.age = age;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "Person{" +
"age=" + age +
'}';
}
}
2.测试
Arrays有方法public static <T> void sort(T[] a, Comparator<? super T> c)
@Test
public void test2() {
Person[] peoples = new Person[4];
peoples[0] = new Person( 13);
peoples[1] = new Person(19);
peoples[2] = new Person(17);
peoples[3] = new Person(16);
Arrays.sort(peoples, new Comparator<Person>() {
@Override
public int compare(Person person1, Person person2) {
return person1.getAge() - person2.getAge();
}
});
System.out.println(Arrays.toString(peoples));
}