I just learn up to tree and one thing I don't understand about it is the class declaration:
for example: class BinarySearchTree<T extends Comparable<? super T>>
.
Now, can you please explain me what is in the bracket and the "<? super T>
"?
Any good source you can refer me to? Thanks.
<? super T>
means that?
is the parent ofT
. If?
is known (for exampleX
), you can use<T extends X>
EDIT: This is good source for Java Generic: http://java.sun.com/j2se/1.5/pdf/generics-tutorial.pdf
The <> brackets are for what's called generics. This is alot like a template in C++ and alows you to create a single data structure that can be strongly typed. For example, the ArrayList object uses a generic to define what type of items are in the ArrayList:
When you are defining a structure that makes use of generics you use to notation above. The "T" is a placeholder for some class that is filled in when the class is instantiated and given a type. For example, the definition of ArrayList might look something like this:
The simplest way is to simply use
MyGeneric<T>
and let any class be used. However, sometime you only want the gereric to be used with classes in a certain inheritence structure. In this specific caseComparable<? super T>
means that this is going to be an object that extend Comparable the Compares any type of object that matches T or is a super-class of T.This declares a class with a single generic type parameter. Since for the binary search tree it's imperative that it can compare two items, this needs to be specified so that the compiler can verify it.
The part in angle brackets is the type parameter
T
and a constraint for it which says:T
is, it should extendComparable
(<T extends Comparable<...>>
).Comparable
should be able to compare itself to eitherT
or a super-class ofT
(<? super T>
).Since
T
could usually be anything this constrains the choice to types where it makes sense to implement a search tree for.Sun's Tutorial is a good place to start learning about wildcards and generics.
Java Ranch is also very good for Java "Greenhorns".
The phrase
<? super T>
is a wildcard and implies that ,class BinarySearchTree can take:a. a type parameter (T) that extends Comparable
b. and also can take a subtype (S) whose parent extends Comparable
The construct
<? super T>
extends utility of class BinarySearchTree to type(s) that implements Comparable and its subtypes.Below code snippet demonstrates this:
With the above declaration the statement
Helper<Animal> x = new Helper<Animal>()
works fine.But the statement:
Helper<Mammal> x = new Helper<Mammal>()
gives the compile errortype parameter Mammal is not within its bound
(the compiler version is javac 1.5.0_06)
When the declaration of the class Helper is changed to below form:
then the statement
Helper<Mammal> x = new Helper<Mammal>()
doesn't give any compiler error.Thus usage of wildcard maximizes the utility of the class.