我正在通過(guò)一些示例來(lái)學(xué)習(xí) Java,但似乎我無(wú)法使用它Collections.sort來(lái)對(duì)我的列表進(jìn)行排序。目前,我的代碼如下:// 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; }} *請(qǐng)注意,帶有省略號(hào)的注釋用于縮寫不相關(guān)的部分我懷疑的是 Person 類toCompare可能是問(wèn)題,因?yàn)樗诒容^字符串...但是,我在網(wǎng)上查找了它,似乎比較兩個(gè)不同的字符串對(duì)于.compareTo方法是有效的。我嘗試將 ArrayList 轉(zhuǎn)換為 List,但仍然出現(xiàn)相同的錯(cuò)誤。我不知道,所以如果有人對(duì)解決這個(gè)問(wèn)題有任何建議,我不想這樣做。先感謝您。
沒(méi)有找到適合 Collections.sort() 的方法
慕尼黑5688855
2024-01-05 19:59:42