1

I want to implement a generic type binary search tree. The declarations are as follow:

public BTNode<T> {}

public class BinaryTree<T extends Comparable<T>> {}

public class BinarySearchTree <T extends Comparable<T>> extends BinaryTree<T> {}

Now I have written a class called Entry and want to store the instances of this class in the BinarySearchTree.

public class Entry implements Comparable{
private String firstName, lastName, address, phoneNumber;

public Entry(String fName, String lName, String address, String phoneNum) {
    this.firstName = fName;
    this.lastName = lName;
    this.address = address;
    this.phoneNumber = phoneNum;
}

public int compareTo(Object arg0) {
    // TODO Auto-generated method stub
    return 0;
}
}

But when I declare BinarySearchTree<Entry> bst, there is always an compile error saying:

"Bound mismatch : The type Entry is not a valid substitute for the bounded parameter > of the type BinarySearchTree"

I am still quite new to the generic type in Java. Can anybody help me solve the problem? Thanks

4
  • 1
    <T extends Comparable<T>> this line in your interface should be <T implements Comparable<T>> Commented Jun 5, 2012 at 13:47
  • 1
    no, <T extends Comparable<T>> is correct! Commented Jun 5, 2012 at 13:52
  • 1
    @HunterMcMillen no it should not: extends is used in generics regardless of classes or interfaces. If you want to say T that extends Foo implements Bar, then you use <T extends Foo & Bar> Commented Jun 5, 2012 at 13:53
  • for best results use <T extends Comparable<? super T>> Commented Jun 5, 2012 at 18:35

2 Answers 2

6

Your Entry class needs to implement Comparable<Entry> instead of the raw Comparable, as the raw Comparable doesn't match Comparable<T>.

public class Entry implements Comparable<Entry> { ... }
Sign up to request clarification or add additional context in comments.

Comments

5

Make your Entry class implement Comparable<Entry> so that it conforms to the contract of BinaryTree.

The contract says "all types T that extend (or implement) the type Comparable<T>". Of you replace "T" with "Entry", you see that this is required: Entry extends Comparable<Entry>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.