Search code examples
javagenericscomparable

Bound mismatch when using <Item extends java.lang.Comparable<Item>>


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

This is where I am getting the error:

public class BinaryTree<Integer> {
  private BTNode<Integer> root;
  //...
}

This is the class I am using:

public class BTNode<Item extends java.lang.Comparable<Item>> implements java.lang.Comparable<BTNode<Item>> {
  private Item data;
  //...
}

I think the Integer wrapper should satisfy the condition <xx extends Comparable<xx>>. Is my understanding wrong? Can you please tell me what I am doing wrong here?

Just for the record, I am using java.lang.Comparable and not my own implementation of Comparable.


Solution

  • Here is the issue:

    public class BinaryTree<Integer> {
        private BTNode<Integer> root;
    }
    

    The class parameter is named Integer. When declaring BTNode<Integer>, you are not referencing java.lang.Integer but the parameter instead.

    I don't really know what you're trying to do, but one advice: better use one single letter to name your classes parameters. For example, no error occurs when using:

    public class BinaryTree<T> {
        private BTNode<Integer> root;
    }
    

    If you wanted root to really use the class parameter, then:

    public class BinaryTree<T extends Comparable<T>> {
        private BTNode<T> root;
    }
    

    Have a look at the following lesson: http://docs.oracle.com/javase/tutorial/extra/generics/index.html