2
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?

Numerator
  • 1,389
  • 3
  • 21
  • 40
  • I assume that `pushAll` is actually defined *within* `Stack`, right? – Joachim Sauer Aug 31 '11 at 09:13
  • @Nir: Please choose a better question title. There are actually several other question here on SO with exactly the same title that ask a different things (actually, one of them asks almost exactly the same thing, so I vote to close as duplicate). – Björn Pollex Aug 31 '11 at 09:15
  • possible duplicate of [Generics in Java](http://stackoverflow.com/questions/1794842/generics-in-java) – Björn Pollex Aug 31 '11 at 09:16
  • 1
    @Björn: while the *reason* and *explanation* is the same, the *question* is a different one. – Joachim Sauer Aug 31 '11 at 09:18
  • @Joachim: The titles match exactly, and I believe if the OP had read that question, he might not have asked this one. – Björn Pollex Aug 31 '11 at 09:19

3 Answers3

12

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.

Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
1

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.

Gambrinus
  • 2,140
  • 16
  • 26
1

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.

Community
  • 1
  • 1
Björn Pollex
  • 75,346
  • 28
  • 201
  • 283