Well, the compiler's right :) You can't call compareTo
directly. However, depending on the version of Java you're using, you can use Integer.compare
(introduced in 1.7) and Double.compare
(introduced in 1.4).
For example:
return Integer.compare(o1C.getPrice(), o2C.getPrice());
If you're not on 1.7 and still want to use built-in methods, you could use:
Integer price1 = o1C.getPrice();
Integer price2 = o2C.getPrice();
return price1.compareTo(price2);
... but this will use unnecessary boxing. Given that sorting a large collection can perform really quite a lot of comparisons, that's not ideal. It may be worth rewriting compare
yourself, until you're ready to use 1.7. It's dead simple:
public static int compare(int x, int y) {
return x < y ? -1
: x > y ? 1
: 0;
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…