1

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.

4
  • 2
    I will also suggest a rename: TreeDB. According to Java conventions, class names should be in CamelCase. Commented Oct 7, 2013 at 3:57
  • 1
    Side note: Take a look [here] if you would like T to implement few interfaces and maybe extend some class. Commented Oct 7, 2013 at 4:06
  • 1
    You almost certainly want Comparable, and not Comparator. Commented Oct 7, 2013 at 6:36
  • What makes you say that? I don't really know the difference between the two. Commented Oct 7, 2013 at 13:29

4 Answers 4

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I also think that it is more reasonable to have T being Comparable, instead making T a Comparator of T itself.
2

try this

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

1 Comment

it makes very little sense for a type to be a comparator of itself
2

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

}

5 Comments

it makes very little sense for a type to be a comparator of itself
@newacct Why not? For a trivial case, what if someone wants to order a couple of objects of same type by putting them in a TreeSet?
@NishantShreshth: and that type also serves as a comparator of that type?
@newacct I totally missed that (subtle) thing. It still took me to write a small snippet to believe it.. :-) Thanks for pointing out.
I got confused between Comparator and Comparable. Also, during an add operation such a type will be rejected by TreeSet (type not comparable).
1

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

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.