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

前端 未结 3 1303
感情败类
感情败类 2021-01-22 10:06
public class Stack {
    public Stack () {....}
    public void push (E e) {....}
    public E pop () {....}
    public boolean isEmpty(){....}
}

public void p         


        
3条回答
  •  天涯浪人
    2021-01-22 10:45

    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 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.

提交回复
热议问题