编程语言
首页 > 编程语言> > java-为什么Collections.binarySearch()不能与之媲美?

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,java,collections,generics,binary-search
来源: https://codeday.me/bug/20191012/1903496.html