1

我有这个Player实现Comparable接口的类。然后我有一个ArrayLists Player。我试图binarySearch()在 s 的列表中Player找到一个Player,但 Java 给了我一个“ cannot find symbol: method 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() 时,它起作用了。

4

2 回答 2

13

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

代替:

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

采用

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

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

于 2009-12-17T21:40:18.043 回答
1

只要您正在实现Comparable,您就可以通过覆盖and来compareTo()保持一致。在这种情况下,这特别容易,因为您可以简单地委托给. 此外,如果您需要包含以下实例,这很方便:equals()equals()hashCode()StringMapPlayer

class Player implements Comparable<String> {

    private String username;
    private String password;

    // ...

    @Override
    public int compareTo(String name) {
        return username.compareTo(name);
    }

    @Override
    public boolean equals(Object obj) {
        return obj instanceof Player
            && username.equals(((Player)obj).username);
    }

    @Override
    public int hashCode() {
        return username.hashCode();
    }
}
于 2009-12-18T03:32:40.050 回答