字符串 1,1-1,1-1-1,1-1-2, 1-2,1-2-1,....1-10,1-11,1-11-1,1-11-2,1-12。
我用
public class TreeIndexComparatorSimpleAsc implements Comparator<TreeModel> {public int compare(TreeModel o1, TreeModel o2) {
return o1.getTreeIndex().compareTo(o2.getTreeIndex());}}然后用Collections.sort(tree, new TreeIndexComparatorAsc())调用 结果排列为
1,1-1,1-10,1-1-1,1-1-2, 1-2,1-2-1,....,1-11,1-11-1,1-11-2,1-12。
1-10在前面了
有没有办法把这个排列顺序改为1,1-1,1-1-1,1-1-2, 1-2,1-2-1,....1-10,1-11,1-11-1,1-11-2,1-12。呢?

解决方案 »

  1.   

    自己写个Compare类去负责做大小比较就行了。因为字符串比较的话主要靠ASCII码,所以:  "1" < "10" < "100" < "11" < "110" < "111" < "2"
      

  2.   


    package net.csdn;import java.util.Arrays;
    import java.util.Comparator;class Test {
    public static void main(String[] args) { String[] index = { "1-1", "1-2", "1-1-10", "1-3", "1-1-2", "1-2-3", "1-2-2", "2-1" };
    Arrays.sort(index, comparator);
    System.out.println(index.toString());
    } static Comparator comparator = new Comparator() { public int compare(Object o1, Object o2) {
    String[] s1Arr = o1.toString().split("-");
    String[] s2Arr = o2.toString().split("-");
    int min = Math.min(s1Arr.length, s2Arr.length);
    for (int i = 0; i < min; i++) {
    int i1 = Integer.parseInt(s1Arr[i]);
    int i2 = Integer.parseInt(s2Arr[i]);
    if (i1 != i2) {
    return i1 - i2;
    }
    }
    return -1;
    }
    };
    }