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.

Morgan Kenyon
  • 3,072
  • 1
  • 26
  • 38
  • 2
    I will also suggest a rename: TreeDB. According to Java conventions, class names should be in CamelCase. – Trein Oct 07 '13 at 03:57
  • 1
    Side note: Take a look [[here](http://stackoverflow.com/questions/745756/java-generics-wildcarding-with-multiple-classes/745769#745769)] if you would like `T` to implement few interfaces and maybe extend some class. – Pshemo Oct 07 '13 at 04:06
  • 1
    You almost certainly want `Comparable`, and _not_ `Comparator`. – Louis Wasserman Oct 07 '13 at 06:36
  • What makes you say that? I don't really know the difference between the two. – Morgan Kenyon Oct 07 '13 at 13:29

4 Answers4

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.

Vidya
  • 29,932
  • 7
  • 42
  • 70
  • I also think that it is more reasonable to have `T` being `Comparable`, instead making `T` a `Comparator` of `T` itself. – Adrian Shum Oct 07 '13 at 08:02
2

try this

class treeDB <T extends Comparator<T>> {
...
Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
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>> {

}
  • it makes very little sense for a type to be a *comparator* of itself – newacct Oct 08 '13 at 08:55
  • @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? –  Oct 08 '13 at 10:59
  • @NishantShreshth: and that type also serves as a comparator of that type? – newacct Oct 08 '13 at 11:00
  • @newacct I totally missed that (subtle) thing. It still took me to write a small snippet to believe it.. :-) Thanks for pointing out. –  Oct 08 '13 at 11:15
  • I got confused between `Comparator` and `Comparable`. Also, during an add operation such a type will be rejected by TreeSet (type not *comparable*). –  Oct 08 '13 at 11:23
1

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

Debojit Saikia
  • 10,532
  • 3
  • 35
  • 46