java - "Type mismatch"将 Java 泛型与通配符一起使用时

标签 java generics

我在 Java 中使用泛型时遇到一个奇怪的问题。泛型对我来说很新,但我想我了解基础知识。

请看这段代码:

private void drawQuadtreeBoxes_helper(QuadTree<?> node) {
    if (node == null)
        return;

    Vector3 min = node.bbox.min;
    Vector3 max = node.bbox.max;
    // Draw the boxes (...)

    if (node.hasChildren()) {
        Array<QuadTree<?>> children = node.getChildren(); // ERROR HERE
        for (QuadTree<?> child : children) {
            drawQuadtreeBoxes_helper(child);
        }
    }
}

因为存储在四叉树结构中的对象类型与该方法无关,所以我使用通配符作为方法签名,以便该方法适用于所有类型的四叉树。

getChildren() 方法返回节点的四个子节点,存储在名为 Array (implementation of Array) 的集合类中。我确定 getChildren() 的返回类型确实是 Array<QuadTree<?>> (甚至 Eclipse 在工具提示中也是这样说的),但我仍然在这一行上遇到错误,告诉我:

cannot convert from Array<QuadTree<capture#6-of ?>> to Array<QuadTree<?>>

有趣的部分来了:当我向 Eclipse 询问如何解决这个问题时,这是其中一个建议:

Change type of 'children' to 'Array<QuadTree<?>>'

但它已经是这种类型了!它变得更好了:当我点击这个建议时,Eclipse 将这一行更改为:

Array<?> children = node.getChildren();

当然,这会破坏下面所有的代码。

这到底是怎么回事?请哪位大侠指教一下?

最佳答案

问题是方法不知道它是相同 QuadTree<?> (? 可以引用同一调用中的不同 类型)。

解决方案是“键入”方法,该方法锁定在QuadTree<?>。 (因此 ?)在整个方法中都是相同类型。

private <T extends QuadTree<?>> void drawQuadtreeBoxes_helper(T node) {
    if (node == null)
        return;

    Vector3 min = node.bbox.min;
    Vector3 max = node.bbox.max;
    // Draw the boxes (...)

    if (node.hasChildren()) {
        Array<T> children = node.getChildren(); // ERROR HERE
        for (T child : children) {
            drawQuadtreeBoxes_helper(child);
        }
    }
}


?仍然表示“任何东西”,但现在相同“任何东西”。

关于java - "Type mismatch"将 Java 泛型与通配符一起使用时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11367979/

相关文章:

c# - 从方法泛型推断类型

generics - 带有数组的 Swift countElements()

.net - 是否可以在将自身指定为泛型类型参数的同时发出从泛型类型派生的类型?

java - 如何使用 JMX 监控现有的 Java 类?

java - 有没有办法在 Eclipse 中抑制 "The type (...) collides with a package"警告?

android - 我应该使用哪个 JDK 来编译我的 Android 应用程序以及哪个版本?

java - 如何向按钮的recycleview添加onItemclicklistener方法

Java OpenCV 将小图像分层到具有透明度的大图像上

ios - 使用 Swift 泛型创建新的 NSManagedObjects

Java 泛型和流