3 回答
TA貢獻(xiàn)1830條經(jīng)驗 獲得超9個贊
使用方法定義一個接口Identifiable(或超類 Person)int getId()。
使您的所有類都實現(xiàn)該接口(或擴(kuò)展該超類)。
停止使用原始類型,因此使用 aList<Identifiable>而不是 a List。
然后使用 a 對列表進(jìn)行排序Comparator<Identifiable>,可以使用Comparator.comparingInt(Identifiable::getId).
你所有的類都不應(yīng)該實現(xiàn) Comparable。它們的 ID 沒有定義它們的自然順序。在這個特定的用例中,您只是碰巧按 ID 對它們進(jìn)行排序。因此應(yīng)該使用特定的比較器。
TA貢獻(xiàn)1840條經(jīng)驗 獲得超5個贊
例如Person,定義一個超類,然后在id那里添加您的?;?id 邏輯的比較也應(yīng)該在那里實現(xiàn)。
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用術(shù)語定義您Person并對其應(yīng)用排序。
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);
}
TA貢獻(xiàn)1820條經(jīng)驗 獲得超10個贊
創(chuàng)建像 person 這樣具有 id 屬性的類。然后通過它擴(kuò)展所有這些類。那么你只需要為 person 類編寫比較
添加回答
舉報
