Morgan Kenyon
Morgan Kenyon

Reputation: 3172

Java Generics Comparator

I am coding with Java Generics. I want to define a Binary Tree class generically that will be able to take in any class , and guarantee that that class has the Comparator method compare(T o1, T o2) to see whether I need to follow the right or left subtree for insert into my binary tree.

public class treeDB <T implements Comparator> {
    //define my binary tree methods
}

That is my best estimation of how to force to implement Comparator method, but the compile throws an error and I don't know enough to know what it wants.

Upvotes: 1

Views: 2420

Answers (4)

user2030471
user2030471

Reputation:

Firstly, implements should be replaced with extends. In generics extends is the keyword which is used even if the generic type implements an interface.

And secondly, using only Comparator will result in a warning it being a raw type. You must parameterize it. This is your solution:

public class treeDB <T extends Comparator<T>> {

}

Upvotes: 2

Vidya
Vidya

Reputation: 30310

Everyone has provided the correct syntax, but you might want to consider using Comparable as in

class treeDB <T extends Comparable<T>>

The differences are subtle, and maybe it isn't the better choice. But it never hurts to look.

Upvotes: 3

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136022

try this

class treeDB <T extends Comparator<T>> {
...

Upvotes: 2

Debojit Saikia
Debojit Saikia

Reputation: 10632

This should be public class treeDB <T extends Comparator>, not public class treeDB <T implements Comparator>.

Upvotes: 1

Related Questions