我想根据权重进行排序,但是compareto()方法不起作用,但是当我在pojo中将权重类型更改为“integer”时,它就起作用了。有人能给我解释一下发生了什么事吗?请在下面找到我的代码
public class CollectionsDemo {
public static void main(String[] args) {
List<Apple> appleList = Arrays.asList(
new Apple(10, "green"),
new Apple(60, "green"),
new Apple(150, "green"),
new Apple(155, "red"),
new Apple(175, "red"),
new Apple(110, "green"));
//sorting
appleList.sort(new Comparator<Apple>() {
@Override
public int compare(Apple o1, Apple o2) {
return o1.getWeight().compareTo(o2.getWeight()); //compareTo() won't come up in suggestions
//return o1.getColor().compareTo(o2.getColor()); //this is working
}
});
}
}
public class Apple {
private int weight; //changing to Integer works
private String color;
//getters
//setters
}
1条答案
按热度按时间wtzytmuj1#
作为一个整数(
int
)是java中的一个原语,它不(也不能)实现Comparable
接口。你应该使用Integer.compare
比较方法如下: