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?
Your code specified that it only accepts a
Collectionwith the same type parameter as theStackhas.You should write the
pushAllmethod like this:This means that you expect a
Collectionof some type that extendsE(i.e. you don’t care what specific type it is, but it must beEor some sub-type of it).Look at the definition of
Collection.addAll(): it’s defined in the same way.