java - 泛型和 <E extends ...> 的问题

标签 java generics

我有两个这样的类(class)

public class Wire<E extends Electricity> implements Connection<E> {
    private ArrayList<Inlet<E>> outlets = new ArrayList<Inlet<E>>();

    public void outputToAll() {     
        for (Inlet<E> inlet : outlets){
            inlet.addToStore(new Electricity(amountPer));
        }
    }
}

public abstract class Inlet<E> {    
    private E store;

    public void addToStore(E inputObj){
       this.store.add(inputObj);
   }
}

Inlet 没有任何错误,但 Wire 给了我错误

The method addToStore(E) in the type Inlet is not applicable for the arguments (Electricity)

但是,由于outputToAll中的E必须扩展电力,因此Inlet至少是Inlet,为什么将Electricity对象传递给addToStore不起作用?

如果编译器不够聪明,无法知道这是否有效,那么什么是好的解决方法?

最佳答案

您不需要 Wire 类对于您想要做的事情是通用的。

如果你有:

public class Wire implements Connection<Electricity> {
    private ArrayList<Inlet<Electricity>> outlets = new ArrayList<Inlet<Electricity>>();

    public void outputToAll() {     
        for (Inlet<Electricity> inlet : outlets){
            inlet.addToStore(new Electricity(amountPer));
        }
    }
    ...
}

这个类(可能,因为我看不到它的其余部分)也适用于 Electricity 的子类,因为 Liskov substitution principle .

关于java - 泛型和 <E extends ...> 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36816496/

相关文章:

java - 使用eclipse通过接口(interface)在方法中添加默认代码

java - 在 Mac OS 上将 eclipse rcp 应用程序从 3.3 升级到 3.5 时出现问题

java - 如何在使用激活器/sbt 的低测试覆盖率上失败?

java - Java、Android 上的 Android Facebook SDK 出现问题

scala - 为什么 deriveHCons 的签名在 Symbol 是最终类时声明 `HK <: Symbol`

java - 与提供者和不可变对象(immutable对象)的深度映射

c# - 一种泛型类型的多个 where 约束

Java 泛型运行时实例化

java - 通用辅助方法与直接类转换?

function - 将类型信息放入 Scala 中的空参数方法调用