没有找到适合 Collections.sort() 的方法

No suitable method found for Collections.sort()

我正在通过一些示例来学习 Java,但我似乎无法使用 Collections.sort 对我的列表进行排序。目前,我的代码如下:

// Person class in package application.domain

package 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 implementation

package 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;
    }
} 

具有以下输出:

*注意,带省略号的注释用于省略不相关的部分

我怀疑人 class 的 toCompare 可能是问题所在,因为它正在比较字符串...但是,我在网上查了一下,似乎比较两个不同的字符串对 .compareTo 方法有效。我尝试将 ArrayList 转换为 List,但仍然有同样的错误。我不知道所以如果有人对解决这个问题有任何建议,我不想。提前谢谢你。

您可以从 Comparable:

扩展 Identifiable 接口
public interface Identifiable extends Comparable<Identifiable> {
    String getID();  
}

现在您也不需要在 Person class 中实现 Comparable,并且 Collections.sort() 现在应该可以工作了

您可以只在第一个 java 文件中添加一行:

import java.lang.*

我遇到了和你一样的错误,我按照上面的方法解决了。我认为发生这种情况的原因是编译器无法识别客户的 compareTo 函数。