1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
| Student student1 = new Student(1, "d1", 11, 200); Student student2 = new Student(2, "a2", 12, 300); Student student3 = new Student(3, "f3", 13, 15); Student student4 = new Student(4, "f4", 14, 10); Student student5 = new Student(5, "b5", 15, 50); Student student6 = new Student(6, "c6", 16, 100);
ArrayList<Student> studentList = new ArrayList<Student>();
studentList.add(student1); studentList.add(student2); studentList.add(student3); studentList.add(student4); studentList.add(student5); studentList.add(student6);
Comparator<Student> nameComparator = new Comparator<Student>() { public int compare(Student s1, Student s2) { String name1 = s1.getName(); String name2 = s2.getName(); int result = name1.compareTo(name2); return result; } };
Collections.sort(studentList, nameComparator);
for (Student student: studentList) { System.out.println(student); }
Collections.sort(studentList, new Comparator<Student>() { public int compare(Student s1, Student s2) { int score1 = s1.getScore(); int score2 = s2.getScore(); return score1 - score2; } });
for (Student student: studentList) { System.out.println(student); }
Collections.sort(studentList, new Comparator<Student>() { public int compare(Student s1, Student s2) { int age1 = s1.getAge(); int age2 = s2.getAge(); return age2 - age1; } });
for (Student student: studentList) { System.out.println(student); }
|