java-为什么Collections.binarySearch()不能与之媲美?

我有一个实现Comparable接口的Player类.然后我有一个播放器的ArrayList.我试图使用Player列表上的binarySearch()来找到一个Player,但是Java给我一个“找不到符号:方法binarySearch(java.util.ArrayList< Player> Player)”.

这个Player类:

class Player implements Comparable {

    private String username;
    private String password;
    Statistics stats;

    //Constructor, creates a new Player with a supplied username
    Player(String name) {
        username = name;
        password = "";
        stats = new Statistics();
    }

    //Accessor method to return the username as a String
    String getName() {
        return username;
    }

    String getPassword() {
        return password;
    }

    void setPassword(String newPass) {
        password = newPass;
    }

    //Method to change the username
    void setName(String newName) {
        username = newName;
    }

    public int compareTo(Object o) {
        return username.compareTo(((Player)o).username);
    }
}

奇怪的是,当我在同一列表上尝试Collections.sort()时,它可以工作.

解决方法:

使用不一致地使用泛型.注意编译器警告.始终提供通用参数(或从不提供它们).

代替:

class Player implements Comparable {
    [...]
    public int compareTo(Object o) {

采用

class Player implements Comparable<Player> {
    [...]
    public int compareTo(Player o) {

没有稀有类型的复杂性,泛型规则就足够困难了.因此,如果您将它们混淆,通常语言规范会放弃.

上一篇:Comparable.compareTo的返回值在Java中意味着什么?


下一篇:java – “互相比较”是什么意思?