案例介绍
>ArrayList中存储多个person对象(包括name、age、id)要求按年龄从小到大排序,年龄相等的话按名字的大小排序输出
案例设计
>使用ArrayList来存储person对象
>使用Collections类提供的静态Sort方法来排序,最终输出排序好的结果
import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; public class Dem03 { public static void main(String[] args) { List<Person> data = new ArrayList<>(); data.add(new Person("jack",18,10)); data.add(new Person("jay",20,5)); data.add(new Person("lucy",15,8)); data.add(new Person("rose",21,1)); data.add(new Person("pete",15,12)); /** * 根据指定比较器产生的顺序对指定列表进行排序 */ Collections.sort(data, new Comparator<Person>() { public int compare(Person o1, Person o2) { if(o1.getAge() - o2.getAge()>0) { return 1; }else if(o1.getAge() - o2.getAge()<0) { return -1; }else { return o1.getName().compareTo(o2.getName());//如果年龄相同则通过名字排序,通过调用compareTo按名字字典排序 } } }); /** * 通过增加for循环输出 */ for(Person p:data) { System.out.println(p); } } } class Person{ private String name; private int age; private int id; 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 int getId() { return id; } public void setId(int id) { this.id = id; } public Person(String name, int age, int id) { super(); this.name = name; this.age = age; this.id = id; } @Override public String toString() { return "Person [name=" + name + ", age=" + age + ", id=" + id + "]"; } }