首先建立测试类
public class Person implements Comparable<Person>{
private String name;
private int age;
public Person() {
}
public Person(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 "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
@Override
public int compareTo(Person o) {
return if(o.getAge>age) return -1;
}
public static void main(String[] args) {
List<Person> ps = new LinkedList<>();
ps.add(new Person("张三三",1));
ps.add(new Person("李四四",33));
ps.add(new Person("王五五五",88));
ps.add(new Person("贾六",33));
Collections.sort(ps);
System.out.println(ps.toString());
}
}
在实现Comparable接口的时候,可以发现接口方法里只有 compareTo(Person o)
compareTo的实现格式:
public int compareTo(Person o) {
return age>o.getAge()? -1:1; //降序序排列
//return age>o.getAge()? 1:-1; 升序排列
//return o.getAge()>age? -1:1; //升序排列
//return age>o.getAge()? 1:-1; 降序排列
}
执行方法:
得结果:
多条件排序
年龄相同,名字短的在前面。
@Override
public int compareTo(Person o) {
if( age>o.getAge()){
return -1;
}else if(age ==o.getAge()){//如果年龄相等,按名字判断
if(name.length() > o.getName().length()){
return 1;
}else return -1;
}else return 1;
}
运行得到结果,年龄降序,名字长度升序