Faraz
Faraz

Reputation: 6265

Bound mismatch: The type is not a valid substitute for the bounded parameter <E extends Comparable<E>> of the type

I have a class:

public class BinarySearchTree<E extends Comparable<E>> {
    private TreeNode<E> root;
    //other methods like insert, etc
}

public class TreeNode<V extends Comparable<V>> implements Comparable<V>{
    //left and right instances of TreeNode and data holder V instance. 
    //insert method, etc
    @Override
    public int compareTo(V o) {
        return 0;
    }
}

So far so good.

When I write this code with in class BinarySearchTree,:

public void levelOrderTraversalQueue() {
    Queue<TreeNode<E>> q = new Queue(); //<--Bound mismatch: The type BinarySearchTree<E>.TreeNode<E> is not a valid substitute for the bounded parameter <E extends Comparable<E>> of the type Queue<E>
}

Why is that? My Queue class is implemented like this:

public class Queue<E extends Comparable<E>> {
    private LinkedList<E> list;
    //other operations
}

How do I solve this error?

Upvotes: 1

Views: 1883

Answers (1)

Sweeper
Sweeper

Reputation: 271040

This:

public class TreeNode<...> implements Comparable<V>{

means that a TreeNode can be compared to a V - the thing it is storing.

That's not what you mean. To be able to put a tree node into your Queue, a tree node needs the ability to be compared with another tree node. Recall:

Queue<E extends Comparable<E>>

Whatever E is, it must implement Comparable<E>. Here, E is TreeNode<V>.

Therefore you should write:

public class TreeNode<...> implements Comparable<TreeNode<V>> {

Upvotes: 2

Related Questions