在閱讀開源Java項(xiàng)目源代碼過程中,我發(fā)現(xiàn)Java開發(fā)者經(jīng)常使用兩種開發(fā)方式排序:一種是使用Collections和Arrays類的sort方法,另一種是使用可排序的數(shù)據(jù)結(jié)構(gòu)。
使用sort()方法
1 2 3 4 5 6 7 | // 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()); } }); |
1 2 3 4 5 6 7 | // Arrays.sort ObjectName[] arr = new ObjectName[ 10 ]; Arrays.sort(arr, new Comparator<ObjectName>() { public int compare(ObjectName o1, ObjectName o2) { return o1.toString().compareTo(o2.toString()); } }); |
使用可排序的數(shù)據(jù)結(jié)構(gòu)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | // 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); // 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); |
不好的編程實(shí)踐
也有很多不好的編程實(shí)踐,比如使用自定義的排序算法。下面的代碼不僅算法效率不高,而且可讀性差。
1 2 3 4 5 6 7 8 | 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; } |
聯(lián)系客服