ArrayList<Integer> lists = new ArrayList<>(Arrays.asList(Integer.MAX_VALUE,0,1,1,1,1,-9,-9,-9,-9,0,0,0,0,3,3,3,3,99,999,99,999));
Collections.sort(lists, new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
if(o1>o2)return 1;
else return -1;
}
});
Integer arr[] = new Integer[]{2,3};
Arrays.sort(arr,new Comparator<Integer>(){
@Override
public int compare(Integer o1, Integer o2) {
if(o1>o2)return 1;
else return -1;
}
});
2.真是情况
- 在刷题的过程中会发现这样的写法在大量数据测试面前不能真正的排序。我们查看一下Integer的compare方法。可以看到compare比较有三种情况,1,-1和0,0这种情况不能省掉。Arrays.sort()底层是TimSort排序-一种高效的插入-归并排序。
public static int compare(int x, int y) {
return (x < y) ? -1 : ((x == y) ? 0 : 1);
}
正确的写法应该是:
ArrayList<Integer> lists = new ArrayList<>(Arrays.asList(Integer.MAX_VALUE,0,1,1,1,1,-9,-9,-9,-9,0,0,0,0,3,3,3,3,99,999,99,999));
Collections.sort(lists, new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
if(o1>o2)return 1;
else if(o1==o2) return 0;
else return -1;
}
});
- 还能在骚气一点!
ArrayList<Integer> lists = new ArrayList<>(Arrays.asList(Integer.MAX_VALUE,0,1,1,1,1,-9,-9,-9,-9,0,0,0,0,3,3,3,3,99,999,99,999));
Collections.sort(lists, new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o1-o2;
}
});
3.那样写还不够骚气!
- 在jdk8横空出世了Lambda表达式,可以代替内部类和函数式接口。
ArrayList<Integer> lists = new ArrayList<>(Arrays.asList(Integer.MAX_VALUE,0,1,1,,3,3,3,3,99,999,99,999));
Collections.sort(lists, (o1,o2)->{return o1-o2;});
或者连花括号和结束符都不要了!够骚气了吧!
(Arrays.asList(Integer.MAX_VALUE,0,1,1,,3,3,3,3,99,999,99,999));
Collections.sort(lists, (o1,o2)->o1-o2);
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)