4.10 如何在Java中進行排序開發

weixin_33866037發表於2017-01-22

在分析大量的開源Java專案原始碼時候,我發現Java開發者經常使用兩種方式進行排序。一個是使用Collections或者Arrays的sort()方法,另一個是使用排序的資料結構,比如TreeMap和TreeSet。

1.使用排序方法

如果它是個集合,可以使用集合的sort()方法。

// Collections.sort
List<ObjectName> list = new ArrayList<ObjectName>();
Collections.sort(list, new Comparator<ObjectName>() {
    public int compare(ObjectName o1, ObjectName o2) {
        return o1.toString().compareTo(o2.toString());
    }
});

如果已經配置了集合或陣列,這非常方便。

2.利用排序的資料結構

如果是個list或set,可以利用TreeSet進行排序。

// TreeSet
Set<ObjectName> sortedSet = new TreeSet<ObjectName>(new Comparator<ObjectName>() {
    public int compare(ObjectName o1, ObjectName o2) {
        return o1.toString().compareTo(o2.toString());
    }
});
sortedSet.addAll(unsortedSet);

如果是一個Map,可以使用TreeMap進行排序。TreeMap是按照key進行排序的。

// TreeMap - using String.CASE_INSENSITIVE_ORDER which is a Comparator that orders Strings by compareToIgnoreCase
Map<String, Integer> sortedMap = new TreeMap<String, Integer>(String.CASE_INSENSITIVE_ORDER);
sortedMap.putAll(unsortedMap);
//TreeMap - In general, defined comparator
Map<ObjectName, String> sortedMap = new TreeMap<ObjectName, String>(new Comparator<ObjectName>() {
    public int compare(ObjectName o1, ObjectName o2) {
        return o1.toString().compareTo(o2.toString());
    }
});
sortedMap.putAll(unsortedMap);

這個方法非常有用,如果你為集合做大量查詢操作。排序的資料結構將給出O(logN)的時間複雜度,其低於O(n).

3. 壞的實踐

還有不良的做法,如使用自定義排序演算法。以下面的程式碼為例,不僅演算法不是有效的,而且它是不可讀的。這種情況發生在不同形式的變化中。

double t;
for (int i = 0; i < 2; i++)
    for (int j = i + 1; j < 3; j++)
        if (r[j] < r[i]) {
            t = r[i];
            r[i] = r[j];
            r[j] = t;
        }

相關文章