Can I add to a generic collection of type A values of type B ,which extends A, without any special syntax?

醉酒当歌 提交于 2019-12-02 06:29:47

问题


public class Stack<E> {
    public Stack () {....}
    public void push (E e) {....}
    public E pop () {....}
    public boolean isEmpty(){....}
}

public void pushAll (Collection<E> src) {
    for (E e: src){
        push(e)
    }
}

I don't understand what will the problem if I'll write

Stack<number> numberStack = new Stack<Number>();
Collection<Integer> integers=...
numberStack.pushAll(integers);

Integer extends Number, so I can add a collection of Integers to numberStack. But I was told that this is an error compilation- Why?


回答1:


Your code specified that it only accepts a Collection with the same type parameter as the Stack has.

You should write the pushAll method like this:

public void pushAll (Collection<? extends E> src)

This means that you expect a Collection of some type that extends E (i.e. you don't care what specific type it is, but it must be E or some sub-type of it).

Look at the definition of Collection.addAll(): it's defined in the same way.




回答2:


the problem is that you have two types but only one generic representation (E) so E is Number as well as Integer. Thats confusing him. You need to have the same type for the collection. Rewrite it to

pushAll(Collection<K> src) 

and cast K to E.




回答3:


This problem is due the fact that collections in java are not covariant. There are numerous question on SO about it, such as this one.



来源:https://stackoverflow.com/questions/7254820/can-i-add-to-a-generic-collection-of-type-a-values-of-type-b-which-extends-a-w

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!