Java_集合_ArrayLish Comparator比较排序 小笔记
1 import java.util.ArrayList; 2 import java.util.Collections; 3 import java.util.Comparator; 4 5 class Teacher_Main { 6 public static void main(String[] args) { 7 8 ArrayList<Teacher> teacherList = new ArrayList<Teacher>(); 9 teacherList.add(new Teacher("污老湿", 35)); 10 teacherList.add(new Teacher("污老人", 15)); 11 teacherList.add(new Teacher("污小人", 7)); 12 teacherList.add(new Teacher("污大人", 99)); 13 14 15 Collections.sort(teacherList, new Comparator<Teacher>() { 16 17 @Override 18 public int compare(Teacher o1, Teacher o2) { 19 if (o1.age > o2.age) { 20 return -1; 21 } else if (o1.age < o2.age) { 22 return 1; 23 } 24 return 0; 25 } 26 27 }); 28 for (int i = 0; i < teacherList.size(); i++) { 29 Teacher teacher = teacherList.get(i); 30 System.out.println(teacher); 31 32 } 33 } 34 } 35 36 37 38 39 40 class Teacher { 41 public String name; 42 public int age; 43 44 public Teacher(String name, int age) { 45 this.name = name; 46 this.age = age; 47 } 48 49 @Override 50 public String toString()/*转成字符串类型*/ { 51 return name + ":" + +age; 52 } 53 54 }