Java如何按索引对<Array> <string>进行排序/排序?</string>

时间:2012-04-11 06:34:05

标签: java android arraylist

所以我有这个ArrayList:

list.get(0) == "love"  
list.get(1) == "foo"  
list.get(2) == "make"  
list.get(3) == "links"

我想要的是:

list.get(0) == "links"  
list.get(1) == "make"  
list.get(2) == "foo"  
list.get(3) == "love"

我试过这个但没有工作:

public static void orderDescending(final ArrayList<String> list){
    Collections.sort(list, new Comparator<String>() {
        public int compare(String s1, String s2) {
            Integer i1 = list.indexOf(s1);
            Integer i2 = list.indexOf(s2);
            return i1.compareTo(i2);
        }
    });
 }

4 个答案:

答案 0 :(得分:7)

你可以这样做:

Collections.reverse(list);

答案 1 :(得分:1)

简单地说,

Collections.reverse(list);

答案 2 :(得分:0)

这是一个简单的列表反转算法。如果您不关心算法,请使用Collections.reverse()

public static void reverse(List<String> list) {

    if (list == null) {
        return;
    }

    int size = list.size();
    int mid = list.size() / 2;

    ListIterator<String> fwd = list.listIterator();
    ListIterator<String> rev = list.listIterator(size);

    for (int i = 0; i < mid; i++) {
        String tmp = fwd.next();
        fwd.set(rev.previous());
        rev.set(tmp);
    }
}

答案 3 :(得分:0)

你犯了一个小错误,否则你几乎已经完成了。

您应该尝试“返回 i2 .compareTo( i1 );”

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

public class Reverse {

    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<String>();
        list.add("love");
        list.add("foo");
        list.add("make");
        list.add("links");
        System.out.println(list);
        orderDescending(list);
        System.out.println(list);
    }

    public static void orderDescending(final ArrayList<String> list) {
        Collections.sort(list, new Comparator<String>() {
            public int compare(String s1, String s2) {
                Integer i1 = list.indexOf(s1);
                Integer i2 = list.indexOf(s2);
                // return i1.compareTo(i2);
                return i2.compareTo(i1);
            }
        });
    }
}