编辑:解决了,这是我的一个简单错误。谢谢那些帮助我的人!
我环顾四周,却找不到真正适合我需求的解决方案。我正在编写一种显示列表的max元素的通用方法。教科书已经为该方法提供了一行代码:public static <E extends Comparable<E>> E max(E[] list)
。因此,我将假定我的方法需要将 E[]
作为参数传递(稍后重要)。
这是我的主要类(class),运行良好。它用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[]
,但使用Integer类型的数组解决此问题。现在,就像我之前说的那样,代码对我来说很好用,没有编译器或运行时错误。但是,我的教授希望我们实现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];
}
}
这是我遇到问题的地方。 我遇到了以下错误:
required: E[] found: java.lang.Integer java.lang.Integer cannot be converted to E[]
我的主类如何正常工作,但是在Testing类中出现编译器问题?我不知道为什么会这样,就像我之前说的,我可以通过更改参数类型来解决它,但是有没有办法做到这一点?
谢谢。
最佳答案
您正在使用单个Integer调用expectedMax
,但是该方法接受一个Array。
因此更改Line
Assertions.assertEquals(expectedMax(randX[i]), Question_5.max(randX[i]), "i = " + i);
到Assertions.assertEquals(expectedMax(randX), Question_5.max(randX[i]), "i = " + i);
关于java - 在 “Integer cannot be converted to E[]”中遇到错误,但在其他地方可以使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45953489/