yvetterowe
yvetterowe

Reputation: 1269

generic type binary search tree in java

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

Upvotes: 1

Views: 1315

Answers (2)

nd.
nd.

Reputation: 8932

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>

Upvotes: 5

Mattias Buelens
Mattias Buelens

Reputation: 20159

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> { ... }

Upvotes: 6

Related Questions