簡體   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