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

Error sorting list using Comparator

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

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

按字母顺序,测试 10 在测试 9 之前

您正在尝试按名称排序。但名称是 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());
                    }
        });

StringcompareTolexicographically比较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());
            }
});