tags:

views:

243

answers:

6

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.

+3  A: 

<? super T> means that ? is the parent of T. If ? is known (for example X), 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

nanda
+9  A: 

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:

  • Whatever T is, it should extend Comparable (<T extends Comparable<...>>).
  • Said Comparable should be able to compare itself to either T or a super-class of T (<? super T>).

Since T could usually be anything this constrains the choice to types where it makes sense to implement a search tree for.

Joey
+1  A: 

Java 5 introduced generics. Check out the wiki page, which has a bunch of good references.

toolkit
A: 

Sun's Tutorial is a good place to start learning about wildcards and generics.

Java Ranch is also very good for Java "Greenhorns".

Gordon
A: 

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:

ArrayList<String> - an ArrayList containing Strings
ArrayList<MyClass> - an ArrayList containing MyClass objects

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:

public class ArrayList<T> ...

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 case Comparable<? 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.

dball917
This is also a helpful asnwer thanks
gingergeek
A: 
sateesh