编辑:已解决,这是我的一个简单的错误。感谢那些帮助过我的人!获取错误“整数不能转换为E []”,但在别处工作?
我环顾四周,找不到适合我需求的解决方案。我正在编写一个显示列表的最大元素的通用方法。该教科书已经为该方法提供了一行代码:public static <E extends Comparable<E>> E max(E[] list)
。因此,我将假设我的方法要求E[]
作为参数传递(稍后重要)。
这是我的主要类,它运行得很好。它用25个随机整数填充Integer数组,并使用我的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类中遇到了一个编译器问题?我失去了为什么会发生这种情况,就像我之前说过的,我可以通过更改参数类型来修复它,但有没有办法做到这一点?
谢谢。
注意:您的'expectedMax'方法重新排列数组,并返回最小值。最好使用'Collections.max(Arrays.asList(list))'。 –