当我执行下面的代码时,我得到的输出为[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));
}
}
它如何对数字进行排序?
最佳答案
而不是
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;
}
}
您的代码可能会产生溢出。当产生溢出时,您会得到奇怪的顺序。
关于java - 使用 Comparator 和 Arrays.asList() 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31472174/