我可以使用compareTo对整数和双精度值进行排序吗?
我可以使用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; } }
好吧,编译器的权利:)你不能直接调用compareTo
。 但是,根据您使用的Java版本,您可以使用Integer.compare
(在1.7中引入)和Double.compare
(在1.4中引入)。
例如:
return Integer.compare(o1C.getPrice(), o2C.getPrice());
如果您不在1.7并且仍想使用内置方法,则可以使用:
Integer price1 = o1C.getPrice(); Integer price2 = o2C.getPrice(); return price1.compareTo(price2);
…但这将使用不必要的拳击。 鉴于对大型集合进行排序可以进行相当多的比较,这并不理想。 在您准备好使用1.7之前,可能值得重写自己compare
。 这很简单:
public static int compare(int x, int y) { return x < y ? -1 : x > y ? 1 : 0; }
更改代码
int price;
至
Integer price;
因为像int
这样的原始类型不支持任何方法,比如compareTo()
。
在您当前的代码中; 更简单的解决方案就是改变这条线,一切都会很好:
return o1C.getPrice() - o2C.getPrice() ;
这样做也会很好,性能也很好,因为方法compare()只有以下要求即。 如果两个值相等则返回零; 否则是正数/负数。