我一直面对这个问题,它开始让我感到沮丧。代码需要返回最接近val的k个元素。如果k为负,则此方法将抛出IllegalArgumentException,如果k == 0或k> 0,则返回零长度的数组。则为a.length。当我针对此方法运行测试用例时,它会报告:
There was 1 failure:
1) nearestKTest(SelectorTest)
java.lang.AssertionError: expected:<[I@12c5431> but was:<[I@14b6bed>
at SelectorTest.nearestKTest(SelectorTest.java:21)
FAILURES!!!
Tests run: 1, Failures: 1
我知道这意味着预期不符合实际情况。我简直无法理解。 :(
public static int[] nearestK(int[] a, int val, int k) {
int[] b = new int[10];
for (int i = 0; i < b.length; i++){
b[i] = Math.abs(a[i] - val);
}
Arrays.sort(b);
int[] c = new int [k];
for (int i = 0; i < k; i++){
if (k < 0){
throw new IllegalArgumentException("k is not invalid!");
}
else if (k == 0 || k > a.length){
return new int[0];}
else{
c[i] = b[i];}
}
return c;
}
Test case:
import org.junit.Assert;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
public class SelectorTest {
/** Fixture initialization (common initialization
* for all tests). **/
@Before public void setUp() {
}
/** A test that always fails. **/
@Test public void nearestKTest() {
int[] a = {2, 4, 6, 7, 8, 10, 13, 14, 15, 32};
int[] expected = {6, 7};
int[] actual = Selector.nearestK(a, 6, 2);
Assert.assertEquals(expected,actual);
}
}
答案 0 :(得分:7)
您正在比较Object
个引用。使用Arrays.equals
比较数组内容
Assert.assertTrue(Arrays.equals(expected, actual));
或JUnit assertArrayEquals
Assert.assertArrayEquals(expected, actual);
正如@Stewart所建议的那样。显然后者更简单。
答案 1 :(得分:3)
使用
Assert.assertArrayEquals(expected, actual);