package mianshi; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; /** * @description * * @author shilvfei * * @date 2018年4月28日 */ public class ArrayListTest { public static void main(String[] args) { User u1 = new User(1,"張三",23); User u2 = new User(3,"李四",24); User u3 = new User(2,"王五",29); User u4 = new User(5,"趙流",21); User u5 = new User(4,"黑八",22); List<User> list = new ArrayList<>(); list.add(u1); list.add(u2); list.add(u3); list.add(u4); list.add(u5); System.out.println("排序前:"); for (User user : list) { System.out.println(user); } //Collections.sort(list, new SortByAge()); //按照年齡排序 Collections.sort(list,new SortByUserId());//按UserId排序 System.out.println("排序後:"); for (User user : list) { System.out.println(user); } } } //年齡排序 class SortByAge implements Comparator<User>{ @Override public int compare(User u1, User u2) { if(u1.getAge()>u2.getAge()){ return 1; } return -1; } } //UserId排序 class SortByUserId implements Comparator<User>{ @Override public int compare(User u1, User u2) { if(u1.getId()>u2.getId()){ return 1; } return -1; } } //User實體 class User { private int id ; private String userName; private int age; public User(int id, String userName, int age) { this.id = id; this.userName = userName; this.age = age; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "User [id=" + id + ", userName=" + userName + ", age=" + age + "]"; } }