Water2Wine

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

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只支持对数组排序

posted on 2020-08-14 20:43  Water2Wine  阅读(535)  评论(0编辑  收藏  举报