为什么 Collections.binarySearch() 不能与此相媲美?
我有这个 Player 类,它实现了 Comparable 接口。然后我有一个 Player
的 ArrayList
。我试图在 Player
列表中使用 binarySearch()
来查找一个 Player
,但 Java 给了我一个“找不到符号:方法binarySearch(java.util.ArrayList
”。
这是 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() 时,它起作用了。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用泛型的方式不一致。注意编译器警告。始终提供通用参数(或从不提供它们)。
而不是:
使用
泛型的规则已经足够困难了,没有罕见类型的复杂性。因此,如果你混淆了它们,通常语言规范就会放弃。
Use are using generics inconsistently. Take heed of the compiler warnings. Always supply generic arguments (or never supply them).
Instead of:
Use
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.
只要您实现 Comparable,您还可以通过覆盖
equals()
和hashCode()
使compareTo()
与equals()
保持一致。在这种情况下,这特别容易,因为您可以简单地委托给String
。此外,如果您需要包含Player
实例的Map
,这会很方便:As long as you are implementing Comparable, you can make
compareTo()
consistent withequals()
by also overridingequals()
andhashCode()
. This is particularly easy in this case, as you can simply delegate toString
. Moreover, it's convenient if you ever need aMap
containing instances ofPlayer
: