我正在通過一些示例來學習 Java,但似乎我無法使用它Collections.sort來對我的列表進行排序。目前,我的代碼如下:// Person class in package application.domainpackage application.domain;public class Person implements Identifiable, Comparable<Identifiable> { private String name; private String id; // ...Constructor... // ...Accessors for getName and getPersonID... @Override // from interface "Identifiable" public String getID(){ return getPersonID(); } public int compareTo(Identifiable another) { return this.getID().compareTo(another.getID()); } //... toString ...}// Register class implementationpackage application.domain; import java.util.*;public class Register { private HashMap<String, Identifiable> registered; // ...Constructor - initialize hashmap ... public void add(Identifiable toBeAdded){ this.registered.put(toBeAdded.getID(), toBeAdded); } // get public Identifiable get(String id){ return this.registered.get(id); } // getAll - must be generalized to work public List<Identifiable> getAll(){ return new ArrayList<Identifiable>(registered.values()); } // sortAndGetEverything (ERROR) public List<Identifiable> sortAndGetEverything(){ List<Identifiable> all = new ArrayList<Identifiable>(registered.values()); Collections.sort(all); // <- part of code that gives an error return all; }} *請注意,帶有省略號的注釋用于縮寫不相關的部分我懷疑的是 Person 類toCompare可能是問題,因為它正在比較字符串...但是,我在網上查找了它,似乎比較兩個不同的字符串對于.compareTo方法是有效的。我嘗試將 ArrayList 轉換為 List,但仍然出現相同的錯誤。我不知道,所以如果有人對解決這個問題有任何建議,我不想這樣做。先感謝您。
沒有找到適合 Collections.sort() 的方法
慕尼黑5688855
2024-01-05 19:59:42