5
public class Stack {
    private LinkedList<? extends Number> stack;

    public <T extends Number> void push(T t){
        stack.add(t);
    }

    public <T extends Number>T pop(){
        return stack.removeLast();
    }
}

Both add and remove last method are giving compile time error. Please help me to understand what I'm doing wrong here?

Error at push -

The method add(capture#1-of ? extends Number) in the type LinkedList is not applicable for the arguments (T)

Error at pop -

Type mismatch: cannot convert from capture#2-of ? extends Number to T

Marvin
  • 9,164
  • 3
  • 26
  • 44
G.D
  • 305
  • 5
  • 18
  • Please [edit] your question and include the errors. You should also describe what it is you are trying to achieve, as it stands, this question is off-topic. – Jorn Vernee Apr 19 '17 at 17:47
  • 1
    `?` is not some `T`, just use `Stack` and `T` everywhere in the class –  Apr 19 '17 at 17:48
  • You do not need the generics in this case. You could replace them with the upper bound `Number`. The code would most likely (even if it would compile) lead to some `ClassCastException`s. Imagine you `push(...)` a `Double`, but try to `pop()` an `Integer`... – Turing85 Apr 19 '17 at 17:49
  • Possible duplicate: http://stackoverflow.com/questions/40506817/java-wildcard-capture –  Apr 19 '17 at 17:51
  • As an aside: you should take a look at the [PECS-mnemonic](http://stackoverflow.com/questions/2723397/what-is-pecs-producer-extends-consumer-super). Since your `Stack` is producer and consumer, you most probably want to use either `Number` or make your whole class generic with some `` as described in the answers below. – Turing85 Apr 19 '17 at 17:57

2 Answers2

4

? isn't the same thing as T and you haven't defined T in your class (only for those methods). Therefore I suggest you make the whole Stack class generic as such:

public class Stack<T extends Number> {
  private LinkedList<T> stack;

Then you can use T in your push() and pop() methods.

radoh
  • 4,554
  • 5
  • 30
  • 45
2

Why not just make your whole class generic? like so:

public class Stack <T extends Number>{
    private LinkedList<T> stack;

    public void push(T t){
        stack.add(t);
    }

    public T pop(){
        return stack.removeLast();
    }

}
CraigR8806
  • 1,584
  • 13
  • 21