Comparable java.lang 內比較器
傳入一個對象,與自身進行比較,返回差值 正整數 0 負整數。
實現接口 :public interface Comparable<T>
接口定義的方法:public int compareTo(T o);
舉例:
private static class Student implements Comparable{ int id; private Student(int id){ this.id = id; } @Override public int compareTo(Object o) { return this.id - ((Student)o).id; } } public void studentCompareTo(){ Student s1 = new Student(10); Student s2 = new Student(20); int b = s1.compareTo(s2); System.out.println(String.valueOf(b)); }
Comparator java.util 外比較器
傳入兩個對象,進行比較
實現接口:public interface Comparator<T>
接口定義的方法 int compare(T o1, T o2);
舉例
private static class StudentCom1 implements Comparator<Student> { @Override public int compare(Student o1, Student o2) { return o1.id - o2.id; } } public void studentCompatator() { List<Student> students = new ArrayList<>(); Student student1 = new Student(10); students.add(student1); Student student2 = new Student(20); students.add(student2); Student student3 = new Student(15); students.add(student3); Collections.sort(students, new StudentCom1()); for (Student student : students) System.out.println(student.id); }