2014-03-07 148 views
2

我有一個ArrayList<double[]>排序數組元素

欲列表根據由double[0]

然後按升序對數組

第一排序的數量由double[1]

排序...

最後通過double[n-1]其中n是雙排列的大小

有什麼簡單的方法可以在Java中做到這一點?

考慮數組列表的一個例子具有4個陣列

{1,2,3,4,5} 
{2,3,4,5,6} 
{0,1,2,3,4} 
{0,2,2,3,4} 

在排序之後這將是

{0,1,2,3,4} 
{0,2,2,3,4}//first element(0=0) is the same, it looks at the second element, and 2>1 
{1,2,3,4,5} 
{2,3,4,5,6} 

它將首先查看排序由第一元件,如果是相同的,將看到第二,如此等等。

回答

4

可以使用Arrays.sortCollections.sort取決於你的外表集合是否是一個數組或List,使用自定義比較做到這一點:

public static <T> void sort(T[] a, 
     Comparator<? super T> c) 

只寫一個自定義的比較中double[]。考慮到Java的面向對象的特性,這將是您編寫的實現Comparator的類。

有一個類似的解決方案,涉及Comparable,如果您願意(可能不會)用指定的比較方法將double[]包裝在某些包裝類LexicalDouble中。

private static class Lexical implements Comparator<double[]> { 

    @Override 
    public int compare(double[] o1, double[] o2) { 
     for (int i = 0; i < o1.length && i < o2.length; i++) { 
      if (o1[i] != o2[i]) { 
       return o1[i] - o2[i] > 0 ? 1 : -1; 
      } 
     } 

     if (o2.length != o1.length) { 
      // how to compare these? 
      return o1.length - o2.length; 
     } 
     return 0; 
    } 
} 

public static void main(String[] args) { 
    double[][] a = { { 1, 2 }, { 2, 4 }, { 2, -2 } }; 
    Arrays.sort(a, new Lexical()); 
    } 
+1

謝謝,我仍然不太確定這個答案。有沒有可能有一些示例代碼? – william007

+0

@ william007示例代碼---> http://www.javaprogrammingforums.com/java-se-api-tutorials/182-how-sort-array-using-java-util-arrays-class.html – Joe

+0

@ william007添加了 – djechlin

1

有可以使用的方法包括:

Arrays.sort(); 

對指定的數組數字升序進行排序。