user3629892
user3629892

Reputation: 3046

java: bound mismatch when using generics

I am trying to implement a generic binary tree. Here's the declaration of the node class

public abstract class Node<E extends Comparable<E>> {
}

A concrete Node:

public class BinaryTreeNode extends Node<BinaryTreeNode> implements
        Comparable<BinaryTreeNode> {

    @Override
    public int compareTo(final BinaryTreeNode node) {
        if (this == node) {
            return 0;
        }
        return this.getValue().compareTo(node.getValue());
    }
}

The abstract tree class

public abstract class BinaryTree<T extends Node<T>> {

    /**
     * TODO.
     */
    public BinaryTree() {

    }

    /**
     * TODO.
     * 
     * @param node TODO
     */
    public abstract void addNode(final T node);

    /**
     * TODO.
     * 
     * @param node TODO
     */
    public abstract void removeNode(final T node);

}

This is where I get the bound mismatch, because of the T parameter of Node. I have tried having it extend Comparable, but I jut cant get it to work. How do I need to declare this? I want to make the binary tree be able to work with all classes that extend Node.

Here's a concrete tree:

public class ConcreteBinaryTree extends BinaryTree {

    private Node root;

    @Override
    public void addNode(Node node) {
        // TODO Auto-generated method stub

    }

    @Override
    public void removeNode(Node node) {
        // TODO Auto-generated method stub

    }

}

How do I need to add the type parameters here?

Upvotes: 0

Views: 70

Answers (1)

assylias
assylias

Reputation: 328873

Your BinaryTree class needs to declare T as a Comparable too - you can use a type intersection for that:

public static abstract class BinaryTree<T extends Node<T> & Comparable<T>>

And your ConcreteBinaryTree class could look like this:

public class ConcreteBinaryTree extends BinaryTree<BinaryTreeNode> {
  @Override
  public void addNode(BinaryTreeNode node) { }
  @Override
  public void removeNode(BinaryTreeNode node) { }
}

Upvotes: 5

Related Questions