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

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

我想根据权重进行排序,但是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

        }
wtzytmuj

wtzytmuj1#

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

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

相关问题