有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

带有扩展的java泛型

在:

public class Organic<E> {
    void react(E e) {
    }

    static void main(String[] args) {
        Organic<? extends Elem> compound = new Organic<Elem>();
        compound.react(new Elem());
    }
}

class Elem {}

为什么会出现以下编译错误

The method react(capture#1-of ? extends Elem) in the type Organic<capture#1-of ? extends Elem> is not applicable for the arguments (Elem)


共 (3) 个答案

  1. # 1 楼答案

    根据以下内容修改您的方法,它将起作用:

    void react(Elem e) {
    
    }
    
  2. # 2 楼答案

    那个?当您希望允许用户仅将SomeClass或其子类作为泛型参数传递时,扩展SomeClass’用于定义泛型类型。这意味着您可以这样做:

    public class Organic<E extends Elem> {
        void react(E e) {
    }
    

    如果你想用元素的子类来参数化有机物。在main方法中,您可以执行以下操作:

        Organic<Elem> compound = new Organic<ElemOrAnyElemSubclass>();
    

    正如我所知,没有必要使用

    Organic<? extends Elem>
    

    在方法体中

    完整代码:

    public class Organic<E extends Elem> {
    void react(E e) {
    }
    
    static void main(String[] args) {
        Organic<Elem> compound = new Organic<Elem>();
        compound.react(new Elem());
       }
    }
    class Elem {}
    class ElemSubClass extends Elem {} // if you need
    

    此外,在表达式的左侧和右侧都必须使用相同的泛型类型。这是illehal: 有机化合物=新的有机化合物()

    我不确定这是你想要的,但希望它能帮助你

  3. # 3 楼答案

    http://docs.oracle.com/javase/tutorial/extra/generics/wildcards.html

    列表是有界通配符的一个示例。这个表示未知类型,就像我们前面看到的通配符一样。然而,在本例中,我们知道这个未知类型实际上是Shape的一个子类型。(注意:它可以是Shape本身,也可以是某个子类;它不需要逐字扩展Shape。)我们说形状是通配符的上界

    与往常一样,使用通配符的灵活性需要付出代价。这个代价是,现在在方法体中写入形状是非法的。例如,这是不允许的:

    public void addRectangle(List<? extends Shape> shapes) {
        // Compile-time error!
        shapes.add(0, new Rectangle());
    }
    

    您应该能够理解为什么上面的代码是不允许的。形状的第二个参数的类型。add()是什么?将形状扩展为形状的未知子类型。因为我们不知道它是什么类型,所以我们不知道它是否是矩形的超类型;它可能是也可能不是这样的超类型,因此在那里传递矩形是不安全的

    特别是在讨论您的解决方案时,您不能使用Elem类型的对象调用react,就像使用Organic<? extends Elem>类型一样。您可以合法地分配compound = new Organic<ElemSubClass>()-然后react将导致编译错误,因为您不能通过超类对象调用它