package test;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
class Person {
private String name;
private int age;
private double score;
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 getScore() {
return score;
}
public void setScore(double score) {
this.score = score;
}
public Person(String name, int age, Double score) {
this.name = name;
this.age = age;
this.score = score;
}
public String toString(){
return String.format("name=%s,age=%d,score=%f",name,age,score);
}}
public class CompareToDemo {
public static void main(String[] args) {
List<Person> list = new ArrayList<>();
list.add(new Person("lisi",28,99.5));
list.add(new Person("lisi",27,99.5));
list.add(new Person("haokun",7,90.5));
list.add(new Person("haokun",7,100.0));
list.add(new Person("aoteman",28,95.0));
Collections.sort(list,new Comparator<Person>(){
public int compare(Person p1,Person p2){
/** if(p1.getName().compareTo(p2.getName())!=0){
return p1.getName().compareTo(p2.getName());
}else if(p1.getAge()-p2.getAge()!=0){
return p1.getAge()-p2.getAge();
}else{
return (int)(p1.getScore()-p2.getScore());
}*/
//写法的改进
int nameNum = p1.getName().compareTo(p2.getName());//比较姓名
int ageNum = nameNum == 0 ? p1.getAge() - p2.getAge() : nameNum;//比较年龄
int scoreNum = ageNum == 0 ? (int) (p1.getScore() - p2.getScore()) : ageNum;//比较分数
return scoreNum;
}
});
for(Person p:list){
System.out.println(p);
}
}
}