Skull
Skull

Reputation: 11

Java Generics :The method compareTo(capture#2-of ? extends E) in the type Comparable is not applicable for the arguments (Comparable)

I'm writing generic code to sort the stack but getting warning while calling comareTo:

public class StackUtility {
    public static <E extends Comparable<? extends E>> void sort(IStack<E> stack) {
        IStack<E> stack2 = new MyLinkedStack<>();
        while (!stack.isEmpty()) {
            Comparable<? extends E> e = stack.pop();
            while (stack2.isEmpty() && stack2.peek().compareTo(e)>0) {
                // some code to be written
            }
        }
    }
}

Note: The return type of pop and peek is E.

while calling compareTo I'm getting this warning from Eclipse:

The method compareTo(capture#2-of ? extends E) in the type Comparable is not applicable for the arguments (Comparable)

whats the write way to do that without warning.

Upvotes: 1

Views: 477

Answers (1)

Eran
Eran

Reputation: 393781

E only has to implement Comparable<E> :

public static <E extends Comparable<E>> void sort(IStack<E> stack) {
    IStack<E> stack2=new MyLinkedStack<>();

    while(!stack.isEmpty()){
        E e=stack.pop();
        while(stack2.isEmpty() && stack2.peek().compareTo(e)){
            //some code to be written
        }
    }
}

Upvotes: 2

Related Questions