对集合中的对象进行排序
1.Comparator 外部比较器,需要外部创建比较器对象实现 Comparator 接口
/** * 外部比较器 * 按age由小到大排序 */ class UserComparators implements Comparator<User>{ @Override public int compare(User o1, User o2) { if(o1.age > o2.age) { return 1; }else if(o1.age < o2.age) { return -1; } return 0; } } public class User{ int age; String name; public User(int age, String name) { super(); this.age = age; this.name = name; } public static void main(String[] args) { List<User> list = new ArrayList<>(); for (int i = 0; i < 12; i++) { list.add(new User(new Random().nextInt(210), i+"name")); } System.out.println(list); Collections.sort(list, new UserComparators()); System.out.println(list); } @Override public String toString() { return "User [age=" + age + ", name=" + name + "]"; } }
2.Comparable 内部比较器,需要被比较的对象实现 Comparable 接口
public class User implements Comparable<User>{ int age; String name; public User(int age, String name) { this.age = age; this.name = name; } public static void main(String[] args) { List<User> list = new ArrayList<>(); for (int i = 0; i < 12; i++) { list.add(new User(new Random().nextInt(210), i+"name")); } System.out.println(list); Collections.sort(list); System.out.println(list); } /** * 内部比较器 * 按age由小到大排序 */ @Override public int compareTo(User o) { if(this.age > o.age) { return 1; }else if(this.age < o.age) { return -1; } return 0; } @Override public String toString() { return "User [age=" + age + ", name=" + name + "]"; } }