【问题标题】:Getting error an "Integer cannot be converted to E[]", but works elsewhere?出现错误“整数无法转换为 E []”,但在其他地方工作?
【发布时间】:2017-08-30 06:32:52
【问题描述】:

编辑:已解决,这是我的一个简单错误。感谢那些帮助过我的人!

我环顾四周,并没有真正找到适合我需要的解决方案。我正在编写一个显示列表最大元素的通用方法。教科书已经提供了该方法的一行代码: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[]

为什么我的主类工作得很好,但我在测试类中遇到了编译器问题?我不知道为什么会发生这种情况,就像我之前所说的,我可以通过更改参数类型来解决它,但是有没有办法做到这一点?

谢谢。

【问题讨论】:

  • 注意:您的 expectedMax 方法对数组重新排序,并返回最小值。最好使用Collections.max(Arrays.asList(list))

标签: java arrays generics compiler-errors


【解决方案1】:

您使用单个 Integer 调用 expectedMax,但该方法不包括 Array。

所以换行

Assertions.assertEquals(expectedMax(randX[i]), Question_5.max(randX[i]), "i = " + i);

Assertions.assertEquals(expectedMax(randX), Question_5.max(randX[i]), "i = " + i);

【讨论】:

  • 非常感谢,我不知道我是怎么错过的……感谢您的快速回复。
【解决方案2】:

换行

Assertions.assertEquals(expectedMax(randX[i]), Question_5.max(randX[i]), "i = " + i);

用这条线
Assertions.assertEquals(expectedMax(randX), Question_5.max(randX[i]), "i = " + i);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-21
    • 1970-01-01
    • 1970-01-01
    • 2012-12-20
    • 1970-01-01
    • 2017-07-21
    相关资源
    最近更新 更多