排序 ArrayList [英] Sorting ArrayList

查看:24
本文介绍了排序 ArrayList的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因为我刚开始接触 JAVA,所以我很好奇在 JAVA 中实现排序的最佳选择是什么(对于 ArrayLists).下面我提供我的 PHP 代码.

Since I'm just starting with JAVA, I'm curious what is the best option for implementing sorting in JAVA (for ArrayLists). Below I provide my PHP code.

public int cmp($a, $b) {
    if ( $a[0] < $b[0] ) return 1;
    else if ( $a[0] > $b[0] ) return -1;
    else if ( $a[1] < $b[1] ) return 1;
    else if ( $a[1] > $b[1] ) return -1;
    else return 0;
}

$selected = array();

for ($i=0; $i<$len; $i++) {
    $rank = getRank();
    $cub = getCub_len();
    $selected[] = array($rank,$cub);
}

uasort($selected, 'cmp')

好吧,我用JAVA写了以下代码:

Well, I wrote the following code in JAVA:

ArrayList<ArrayList<Double>> selected = new ArrayList<ArrayList<Double>>();
ArrayList<Double> rank = new ArrayList<Double>();
ArrayList<Double> cub = new ArrayList<Double>();

for (int i=0; i<len; i++) {
 rank.add(getRank(i));
 cub.add(getCub(i));
}

selected.add(0,rank);
selected.add(1,cub);

如何以正确的方式对selected进行排序(类似于PHP函数cmp)?

How to sort selected in the proper way (similarly to PHP function cmp)?

推荐答案

在你的例子上试试这种方式: >

public static void main(String[] args) throws Exception {
        ArrayList<String[]> listOfStringArrays = new ArrayList<String[]>();
        listOfStringArrays.add(new String[] {"x","y","z"});
        listOfStringArrays.add(new String[] {"a","b","c"});
        listOfStringArrays.add(new String[] {"m","n","o"});
        Collections.sort(listOfStringArrays,new Comparator<String[]>() {
            public int compare(String[] strings, String[] otherStrings) {
                return strings[1].compareTo(otherStrings[1]);
            }
        });
        for (String[] sa : listOfStringArrays) {
            System.out.println(Arrays.toString(sa));
        }
        /* prints out 
          [a, b, c]
          [m, n, o]
          [x, y, z]
        */ 

    }

这篇关于排序 ArrayList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆