按数组元素排序

时间:2014-03-07 03:29:21

标签: java

我有ArrayList<double[]>

我想根据数组中的数字按升序对List进行排序

首先按double[0]

排序

然后按double[1]

...

最后是double[n-1],其中n是双数组的大小

在Java中有没有简单的方法呢?

考虑了一个有4个双数组的arraylist的例子

{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}

它首先会按第一个元素排序,如果它是相同的,它会看到第二个,依此类推。

2 个答案:

答案 0 :(得分:4)

您可以使用Arrays.sortCollections.sort来执行此操作,具体取决于您的外部集合是数组还是List,并使用自定义比较器:

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

只需在double[]中编写自定义比较器即可。鉴于Java的面向对象,这将是您编写实现Comparator的类。

如果您愿意(可能不会)使用指定的比较方法将Comparable包装在某个包装类double[]中,则会有类似LexicalDouble的解决方案。< / p>

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 :(得分:1)

您可以使用一种方法:

Arrays.sort();

将指定的数组按数字升序排序。

相关问题