1. 程式人生 > 實用技巧 >關於多引數排序以及api升序降序排序

關於多引數排序以及api升序降序排序

1. 關於多引數排序問題

有兩種方法可以解決多引數排序的問題

第一種是繼承comparable介面,並複寫compareto方法,這樣就可以直接使用Collections.sort()方法進行排序

第二種方法是不繼承任何介面,直接使用Collections.sort(陣列,new Comparator{}),在new的comparator中複寫compare方法即可

public class t2 {

    public static void main(String[] args) {
        // 方法1,tag類繼承comparable介面並複寫compare方法
        ArrayList<tag> arr = new ArrayList<>();
        tag t1 = new tag(3,3,1);
        tag t2 = new tag(2,3,3);
        tag t3 = new tag(3,3,2);
        arr.add(t1);
        arr.add(t2);
        arr.add(t3);
        Collections.sort(arr);
        for (int i = 0;i < arr.size();i++) {
            System.out.println(arr.get(i).i3);
        }
        // 方法2,index類不繼承任何介面,直接使用Collections相關api複寫comparator中的compare方法
        ArrayList<index> arr1 = new ArrayList<>();
        index o1 = new index(3,3,1);
        index o2 = new index(2,3,3);
        index o3 = new index(3,3,2);
        arr1.add(o1);
        arr1.add(o2);
        arr1.add(o3);
        Collections.sort(arr1, new Comparator<index>() {
            @Override
            public int compare(index o1, index o2) {
                return (o1.i1 - o2.i1) * 100 + (o1.i2 - o2.i2) * 10 + (o1.i3 - o2.i3);
            }
        });
        for (int i = 0;i < arr1.size();i++) {
            System.out.println(arr1.get(i).i3);
        }
        Integer[] a = new Integer[2];
        Arrays.sort(a, Collections.reverseOrder());
    }
}

class index{

    int i1,i2,i3;
    index(int l1, int l2, int l3) {
        i1 = l1;
        i2 = l2;
        i3 = l3;
    }

}

class tag implements Comparable {

    int i1,i2,i3;

    tag(int l1, int l2, int l3) {
        i1 = l1;
        i2 = l2;
        i3 = l3;
    }

    @Override
    public int compareTo(Object o) {
        tag t = (tag)o;
        return (this.i1 - t.i1) * 100 + (this.i2 - t.i2) * 10 + (this.i3 - t.i3);
    }
}

2. 關於api升序降序排序

可以使用Arrays.sort和Collections兩種介面

升序:
Arrays.sort( , Collections.reverseOrder()) // 需要注意的是這裡不支援int等基本型別,只能使用Integer然後排序完轉換
Collections.reverse()
降序:
Arrays.sort()
Collections.sort()

不同點是Collections只支援對集合類排序,Arrays只支援對陣列排序