为什么Collections.binarySearch()不能与这个类似? [英] Why isn't Collections.binarySearch() working with this comparable?
问题描述
我有这个 Player
类实现 Comparable
接口。然后我有一个 ArrayList
Player
s。我试图在玩家
的列表中使用 binarySearch()
找到一个 Player
,但Java给我一个无法找到符号:method binarySearch(java.util.ArrayList< Player>,Player)
。 / p>
这是Player类:
class Player implements Comparable {
private String username;
private String password;
统计数据
//构造函数,使用提供的用户名创建一个新的播放器
Player(String name){
username = name;
password =;
stats = new Statistics();
}
//以字符串返回用户名的访问器方法
String getName(){
return username;
}
String getPassword(){
return password;
}
void setPassword(String newPass){
password = newPass;
}
//改变用户名的方法
void setName(String newName){
username = newName;
}
public int compareTo(Object o){
return username.compareTo((Player)o).username);奇怪的是,当我尝试Collections.sort()时,会发生这样的情况:
}
}
$ b <
使用泛型不一致。注意编译器警告。
而不是:
class Player implements Comparable {
[...]
public int compareTo(Object o){
使用
class Player implements可比较的< Player> {
[...]
public int compareTo(Player o){
泛型规则足够困难,没有罕见类型的并发症。所以,通常语言规范放弃,如果你混合它们。
I have this Player
class which implements the Comparable
interface. Then I have an ArrayList
of Player
s. I'm trying to use binarySearch()
on the list of Player
s to find one Player
, but Java is giving me a "cannot find symbol: method binarySearch(java.util.ArrayList< Player>,Player)
".
This the Player class:
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);
}
}
Weird thing, when I try Collections.sort() on this same list, it works.
Use are using generics inconsistently. Take heed of the compiler warnings. Always supply generic arguments (or never supply them).
Instead of:
class Player implements Comparable {
[...]
public int compareTo(Object o) {
Use
class Player implements Comparable<Player> {
[...]
public int compareTo(Player o) {
The rules of generics are difficult enough without the complication of rare types. So, typically the language spec gives up if you mix them up.
这篇关于为什么Collections.binarySearch()不能与这个类似?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!