java 定制排序 Comparator区分从大到小还是从小到大

    xiaoxiao2021-12-12  3

    比如定义一个类,在类中重新定义Collection.sort()排序规则:

    class ComparatorDp implements Comparator{ public int compare(Object obj1, Object obj2) { double temp=obj1.value()-obj2.value(); int a = 0; if (temp>0) { a = -1; //代表obj1在前 } else { a = 1; //代表obj1在后 } return a; } }

    降序排列:obj1-obj2>0的话返回-1,说明按照从大到小排序 升序排列:obj1-obj2>0的话返回1,说明按照从小到大排序

    class ComparatorDp Comparator{ public int compare(Object obj1, Object obj2) { //相当于从小到大排序 大的返回正值,往后放 return obj1.value()-obj2.value(); //相当于从大到小排序,大值返回负值,往前放 return -(obj1.value()-obj2.value()); } }
    转载请注明原文地址: https://ju.6miu.com/read-900217.html

    最新回复(0)