亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

沒有找到適合 Collections.sort() 的方法

沒有找到適合 Collections.sort() 的方法

慕尼黑5688855 2024-01-05 19:59:42
我正在通過一些示例來學習 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,但仍然出現相同的錯誤。我不知道,所以如果有人對解決這個問題有任何建議,我不想這樣做。先感謝您。
查看完整描述

2 回答

?
aluckdog

TA貢獻1847條經驗 獲得超7個贊

您可以Identifiable從以下位置擴展接口Comparable

public interface Identifiable extends Comparable<Identifiable> {
    String getID();  
}

現在您也不需要在類中實現 Comparable Person,并且 Collections.sort() 現在應該可以工作


查看完整回答
反對 回復 2024-01-05
?
catspeake

TA貢獻1111條經驗 獲得超0個贊

您只需在第一個 java 文件中添加一行:

import java.lang.*

我遇到了和你一樣的錯誤,我通過上面提到的解決方案解決了它。我認為發生這種情況的原因是編譯器無法識別客戶的compareTo函數。


查看完整回答
反對 回復 2024-01-05
  • 2 回答
  • 0 關注
  • 255 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號