简体   繁体   English

泛型和<E extends …>

[英]Issue with generics and <E extends …>

I have two classes like this 我有两个这样的班

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));
        }
    }
}

and

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

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

Inlet doesn't have any errors, but Wire gives me the error that 入口没有任何错误,但是Wire给我的错误是

The method addToStore(E) in the type Inlet is not applicable for the arguments (Electricity) Inlet类型的方法addToStore(E)不适用于参数(电性)

However, since in outputToAll E must extend electricity, so Inlet is at least Inlet, why does passing an Electricity object to addToStore not work? 但是,由于outputToAll E中必须扩展电力,所以Inlet至少是Inlet,为什么将Electricity对象传递给addToStore无效?

And if the compiler isn't smart enough to know that this will work, what is a good workaround? 而且,如果编译器不够聪明,无法知道这将起作用,那么什么是好的解决方法?

You don't need the Wire class to be generic for what it seems like you want to do. 您不需要Wire类就可以实现您想做的事情。

If you just have: 如果您只有:

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));
        }
    }
    ...
}

This class will ( likely , as I can't see the rest of it) work for subclasses of Electricity too, due to the Liskov substitution principle . 由于Liskov替代原理 ,该类也可能 (因为我看不到其余部分)也适用于Electricity子类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM