问题描述
当我执行以下代码时,我的输出为[0, -2000000000, 2000000000] 。
import java.util.Arrays;
import java.util.Comparator;
public class SordidSort {
public static void main(String args[]) {
Integer big = new Integer(2000000000);
Integer small = new Integer(-2000000000);
Integer zero = new Integer(0);
Integer[] arr = new Integer[] { big, small, zero };
Arrays.sort(arr, new Comparator<Object>() {
public int compare(Object o1, Object o2) {
return ((Integer) o2).intValue() - ((Integer) o1).intValue();
}
});
System.out.println(Arrays.asList(arr));
}
}
如何对数字进行排序?
1楼
代替
public int compare(Object o1, Object o2) {
return ((Integer) o2).intValue() - ((Integer) o1).intValue();
}
使用以下
public int compare(Object o1, Object o2) {
int x1 = ((Integer) o1).intValue();
int x2 = ((Integer) o2).intValue();
if (x1 < x2) {
return -1;
} else if (x1 == x2) {
return 0;
} else {
return 1;
}
}
您的代码可能会产生溢出。 当产生溢出时,您可以获得奇怪的顺序。
2楼
手动执行比较器有一些微妙之处。
您刚刚遇到了一些有关int类型的问题。
正确比较两个float或double值要困难得多。
如果您不处理-0.0 ,则可能会出现0.0和-0.0顺序。
而且,如果您不处理NaN ,可能会导致灾难(排序后的随机顺序, TreeMap损坏等)。
幸运的是,每种盒装类型中都有现成的静态方法,名为compare : Integer.compare (自Java 7起), Double.compare , Float.compare等。
使用它们,您将永远不会遇到此类问题。
由于Java 8实现比较器要简单得多:您可以使用Comparator.comparingInt这样的辅助方法:
Arrays.sort(arr, Comparator.comparingInt(o -> ((Integer)o).intValue()));
3楼
如下更改代码:
import java.util.Arrays;
import java.util.Comparator;
public class SordidSort {
public static void main(String args[]) {
Integer big = new Integer(2000000000);
Integer small = new Integer(-2000000000);
Integer zero = new Integer(0);
Integer[] arr = new Integer[] { big, small, zero };
Arrays.sort(arr, new Comparator<Object>() {
public int compare(Object o1, Object o2) {
int o1Val = ((Integer) o1).intValue();
int o2Val = ((Integer) o2).intValue();
if(o1Val > o2Val){
return 1;
} else if(o1Val == o2Val){
return 0;
}else{
return -1;
}
}
});
System.out.println(Arrays.asList(arr));
}
}
4楼
您可以将Comparator声明为new Comparator<Integer>()以便将Integer传递给compare函数,然后可以从Integer.compareTo方法中受益。
public static void main(String args[]) {
Integer big = new Integer(2000000000);
Integer small = new Integer(-2000000000);
Integer zero = new Integer(0);
Integer[] arr = new Integer[] { big, small, zero };
Arrays.sort(arr, new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o1.compareTo(o2);
}
});
System.out.println(Arrays.asList(arr));
}