编辑:已解决,这是我的一个简单错误。谢谢那些帮助我的人!
我环顾四周,无法找到符合我需求的解决方案。我正在编写一个显示列表的最大元素的通用方法。教科书已经为该方法提供了一行代码:public static <E extends Comparable<E>> E max(E[] list)
。因此,我将假设我的方法需要 E[]
作为参数传递(稍后重要)。
这是我的主要课程,运行得非常好。它使用25个随机整数填充整数数组,并使用我的max
方法返回最高的元素。
public class Question_5 {
public static void main(String[] args) {
Integer[] randX = new Integer[25];
for (int i = 0; i < randX.length; i++)
randX[i] = new Random().nextInt();
System.out.println("Max element in array \'" + randX.getClass().getSimpleName() + "\': " + max(randX));
}
public static <E extends Comparable<E>> E max(E[] list) {
E temp = list[0];
for (int i = 1; i < list.length; i++) {
if (list[i].compareTo(temp) == 1)
temp = list[i];
System.out.println("i: " + list[i] + " | Temp: " + temp + " | Byte val: " + list[i].hashCode()); // for debugging
}
return temp;
}
在有人提到将参数从E[] list
更改为Integer[] list
之前,我假设教科书要我将其保留在E[]
,但使用整数类型数组这个问题。就像我之前说的那样,代码对我来说很好,没有编译器或运行时错误。
但是,我的教授希望我们实现JUnit测试,所以我继续编写了这段代码:
class Question_5_TEST {
@Test
void max() {
Integer[] randX = new Integer[25];
for (int i = 0; i < randX.length; i++)
randX[i] = new Random().nextInt();
for (int i = 0; i < randX.length; i++) {
Assertions.assertEquals(expectedMax(randX[i]), Question_5.max(randX[i]), "i = " + i);
}
}
private <E extends Comparable<E>> E expectedMax(E[] list) {
Arrays.sort(list);
return list[0];
}
}
这是我遇到问题的地方。我收到编译错误,说明以下内容:
要求:E [] 发现:java.lang.Integer java.lang.Integer无法转换为E []
为什么我的主类工作得很好,但是我在Testing类中遇到了编译器问题?我迷失了为什么会发生这种情况,就像我之前说过的那样,我可以通过改变参数类型来修复它,但有没有办法在没有这样做的情况下做到这一点?
谢谢。
答案 0 :(得分:0)
您使用单个整数调用expectedMax
,但该方法不包含数组。
所以改变行
Assertions.assertEquals(expectedMax(randX[i]), Question_5.max(randX[i]), "i = " + i);
到
Assertions.assertEquals(expectedMax(randX), Question_5.max(randX[i]), "i = " + i);
答案 1 :(得分:0)
替换行
Assertions.assertEquals(expectedMax(randX[i]), Question_5.max(randX[i]), "i = " + i);
用这条线
Assertions.assertEquals(expectedMax(randX), Question_5.max(randX[i]), "i = " + i);