Java 获取一个“错误”;无法将整数转换为E[]”;,但在其他地方工作?
编辑:解决了我的一个简单错误。谢谢那些帮助我的人 我环顾四周,没有真正找到适合我需要的解决方案。我正在编写一个显示列表最大元素的通用方法。教科书已经为该方法提供了一行代码:Java 获取一个“错误”;无法将整数转换为E[]”;,但在其他地方工作?,java,arrays,generics,compiler-errors,Java,Arrays,Generics,Compiler Errors,编辑:解决了我的一个简单错误。谢谢那些帮助我的人 我环顾四周,没有真正找到适合我需要的解决方案。我正在编写一个显示列表最大元素的通用方法。教科书已经为该方法提供了一行代码:publicstaticemax(E[]list)。因此,我将假设我的方法要求将E[]作为参数传递(稍后很重要) 这是我的主课,运行得很好。它用25个随机整数填充整数数组,并使用mymax方法返回最高的元素 public class Question_5 { public static void main(String[] a
publicstaticemax(E[]list)
。因此,我将假设我的方法要求将E[]
作为参数传递(稍后很重要)
这是我的主课,运行得很好。它用25个随机整数填充整数数组,并使用mymax
方法返回最高的元素
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[]
找到:java.lang.Integer
无法将java.lang.Integer转换为E[]
为什么我的主类工作得很好,但我在测试类中遇到了编译器问题?我不明白为什么会发生这种情况,正如我前面所说的,我可以通过更改参数类型来修复它,但是有没有办法不用这样做呢
谢谢。您正在使用单个整数调用
expectedMax
,但该方法不包含数组
那就换线吧
Assertions.assertEquals(expectedMax(randX[i]), Question_5.max(randX[i]), "i = " + i);
到
换行
Assertions.assertEquals(expectedMax(randX[i]), Question_5.max(randX[i]), "i = " + i);
使用此行Assertions.assertEquals(expectedMax(randX),Question_5.max(randX[i]),“i=”+i)代码>非常感谢,我不知道我怎么会错过这个。。。感谢您的快速回复。谢谢您的回复!注意:您的expectedMax
方法对数组重新排序,并返回最小值。最好使用Collections.max(Arrays.asList(list))
。
Assertions.assertEquals(expectedMax(randX), Question_5.max(randX[i]), "i = " + i);
Assertions.assertEquals(expectedMax(randX[i]), Question_5.max(randX[i]), "i = " + i);