我是Java的新手,我遇到了以下问题 . 我需要按升序对整数数组进行排序,以便偶数将在一半中,而奇数在另一半中 .
所以,我有一个特殊的比较器:
static class EvenOddSort implements Comparator<Integer> {
@Override
public int compare(Integer x, Integer y) {
if (x == y) {
return 0;
}
if (y % 2 == 0) {
if (x < y) {
return -1;
} else {
return 1;
}
}
if (x % 2 == 0) {
if (x < y) {
return 1;
} else {
return -1;
}
}
return 0;
}
}
以下排序方法:
public Integer[] sortEvenOdd(Integer[] nums) {
EvenOddSort customSort = new EvenOddSort();
Arrays.sort(nums, customSort);
return nums;
}
我还有以下测试:
@Test
public void testSortEvenOdd1() {
Integer[] nums = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
Integer[] expected = { 2, 4, 6, 8, 10, 1, 3, 5, 7, 9 };
assertArrayEquals(expected, tasks5.sortEvenOdd(nums));
}
当我在 openJDK6
上运行它并在 openJDK7
上成功时它会失败 .
arrays first differed at element [0]; expected:<2> but was:<1> junit.framework.AssertionFailedError: arrays first differed at element [0]; expected:<2> but was:<1>
-
你能帮我把它兼容
openJDK's
吗? -
此外,知道自己做错了会很棒 .
欢迎任何想法!
1 回答
你的整个比较器坏了,我一直看到更多问题 .
做这样的事情:
首先检查它们是不是既奇数也不是两者都是偶数 . 如果它们不同,则根据奇数或偶数进行排序 .
然后,如果它们都是奇数或两者都回退到标准的整数比较功能 .