繁体   English   中英

使用比较器进行错误排序列表

[英]Error sorting list using Comparator

我正在尝试根据我的name属性对对象列表进行排序。 所以我创建了一个比较器,我注意到它没有被排序。 如果使用此错误,请告知。

List<Country> countryList = new ArrayList<Country>();
Country country1 = new Country("TEST1","Washington");
Country country2 = new Country ("TEST10", New Delhi");
Country country3= new Country ("TEST9", London");
countryList.add(country1);
countryList.add(country2);

Collections.sort(countryList,new Comparator<Country>() {
            public int compare(Country o1, Country o2) {
                return o1.getName().compareTo(o2.getName());
            }
});

我被淘汰了,应该换一种方式。

    TEST1 : Washington
    TEST10 : New Delhi
    TEST9 : London

预期是

    TEST1 : Washington
    TEST9 : London
    TEST10 : New Delhi

按字母顺序排列的TEST10在TEST9之前

您尝试在此处按名称排序。 但是名称是TEST1,TEST10和TEST9。 比较时,您将按字母顺序获得订单:

TEST1
TEST10
TEST9

您可以尝试以下代码:

Collections.sort(countryList,new Comparator<Country>() {
                    public int compare(Country o1, Country o2) {
                        if (o1.getName().length() > o2.getName().length()) return 1;
                        if (o1.getName().length() < o2.getName().length()) return -1;

                        return o1.getName().compareTo(o2.getName());
                    }
        });

String compareTo lexicographically用于比较string ,但是您的逻辑需要比较string的长度

Collections.sort(countryList,new Comparator<Country>() {
            public int compare(Country o1, Country o2) {
                if (o1.getName().length() > o2.getName().length()) return 1;
                if (o1.getName().length() < o2.getName().length()) return -1;

                return o1.getName().compareTo(o2.getName());
            }
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM