3 回答

TA貢獻1830條經驗 獲得超9個贊
使用方法定義一個接口Identifiable
(或超類 Person)int getId()
。
使您的所有類都實現該接口(或擴展該超類)。
停止使用原始類型,因此使用 aList<Identifiable>
而不是 a List
。
然后使用 a 對列表進行排序Comparator<Identifiable>
,可以使用Comparator.comparingInt(Identifiable::getId)
.
你所有的類都不應該實現 Comparable。它們的 ID 沒有定義它們的自然順序。在這個特定的用例中,您只是碰巧按 ID 對它們進行排序。因此應該使用特定的比較器。

TA貢獻1840條經驗 獲得超5個贊
例如Person,定義一個超類,然后在id那里添加您的?;?id 邏輯的比較也應該在那里實現。
public class Person implements Comparable<Person> {
private int id;
// getters, setters, compareTo, etc
}
讓你所有的基類都從 Person
public class Student extends Person { ... }
public class Customer extends Person { ... }
public class Employee extends Person { ... }
public class Patient extends Person { ... }
List用術語定義您Person并對其應用排序。
public static void main(String[] args)
{
List<Person> list = new ArrayList<>();
list.add(new Employee(50));
list.add(new Customer(10));
list.add(new Patient(60));
list.add(new Student(90));
list.add(new Employee(20));
list.add(new Customer(40));
list.add(new Patient(70));
list.add(new Student(30));
Collections.sort(list);
System.out.println(list);
}
添加回答
舉報