Java比较器

Comparable接口的使用
为什么String能够使用sort排序?
是因为String,包装类等默认重写了Comparable接口的compareTo方法.
那我们自定义类如何实现排序?
自然排序
import org.junit.Test;
import java.lang.reflect.Array;
import java.util.Arrays;
public class TestPaixu {
@Test
public void test10(){
People[] people = new People[3];
people[0] = new People("wfr",12);
people[1] = new People("wf",18);
people[2] = new People("w",1);
Arrays.sort(people);
System.out.println(Arrays.toString(people));//[People{name='w', age=1}, People{name='wfr', age=12}, People{name='wf', age=18}]
}
}
public class People implements Comparable {
private String name;
private int age;
public People() {
}
public People(String name, int age) {
this.name = name;
this.age = age;
}
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;
}
@Override
public String toString() {
return "People{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
//按照年龄排序
@Override
public int compareTo(Object o) {
if (o instanceof People){
People people = (People) o;
if (this.age>people.age){
return 1;
}else if (this.age<people.age){
return -1;
}else {
return 0;
}
}throw new RuntimeException("传入的数据类型不一致");
}
}
定制排序