G.D
G.D

Reputation: 315

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

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

Upvotes: 5

Views: 6718

Answers (2)

radoh
radoh

Reputation: 4825

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

Upvotes: 5

CraigR8806
CraigR8806

Reputation: 1584

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();
    }

}

Upvotes: 2

Related Questions