我可以使用compareTo来排序整数和双精度值吗?我的系统给了我一个错误,我不能在原始类型int上调用compareTo(int).有任何想法吗?
码:
public int compare(Object o1, Object o2) {
Record o1C = (Record)o1;
Record o2C = (Record)o2;
return o1C.getPrice().compareTo(o2C.getPrice());
}
class Record
public class Record {
String name;
int price;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
}
Run Code Online (Sandbox Code Playgroud)
Jon*_*eet 25
好吧,编译器的权利:)你不能compareTo直接打电话.但是,根据您使用的Java版本,您可以使用Integer.compare(在1.7中引入)和Double.compare(在1.4中引入).
例如:
return Integer.compare(o1C.getPrice(), o2C.getPrice());
Run Code Online (Sandbox Code Playgroud)
如果您不在1.7并且仍想使用内置方法,则可以使用:
Integer price1 = o1C.getPrice();
Integer price2 = o2C.getPrice();
return price1.compareTo(price2);
Run Code Online (Sandbox Code Playgroud)
...但这将使用不必要的拳击.鉴于对大型集合进行排序可以进行相当多的比较,这并不理想.compare在你准备好使用1.7之前,自己可能值得重写.这很简单:
public static int compare(int x, int y) {
return x < y ? -1
: x > y ? 1
: 0;
}
Run Code Online (Sandbox Code Playgroud)
小智 13
更改代码
int price;
Run Code Online (Sandbox Code Playgroud)
至
Integer price;
Run Code Online (Sandbox Code Playgroud)
因为原始类型如int不支持任何方法,比如compareTo().