正在使用集合,无法使compareto()方法正常工作

f3temu5u  于 2021-09-13  发布在  Java
关注(0)|答案(1)|浏览(417)

我想根据权重进行排序,但是compareto()方法不起作用,但是当我在pojo中将权重类型更改为“integer”时,它就起作用了。有人能给我解释一下发生了什么事吗?请在下面找到我的代码

  1. public class CollectionsDemo {
  2. public static void main(String[] args) {
  3. List<Apple> appleList = Arrays.asList(
  4. new Apple(10, "green"),
  5. new Apple(60, "green"),
  6. new Apple(150, "green"),
  7. new Apple(155, "red"),
  8. new Apple(175, "red"),
  9. new Apple(110, "green"));
  10. //sorting
  11. appleList.sort(new Comparator<Apple>() {
  12. @Override
  13. public int compare(Apple o1, Apple o2) {
  14. return o1.getWeight().compareTo(o2.getWeight()); //compareTo() won't come up in suggestions
  15. //return o1.getColor().compareTo(o2.getColor()); //this is working
  16. }
  17. });
  18. }
  19. }
  20. public class Apple {
  21. private int weight; //changing to Integer works
  22. private String color;
  23. //getters
  24. //setters
  25. }
wtzytmuj

wtzytmuj1#

作为一个整数( int )是java中的一个原语,它不(也不能)实现 Comparable 接口。你应该使用 Integer.compare 比较方法如下:

  1. (x < y) ? -1 : ((x == y) ? 0 : 1);

相关问题