Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does this class declaration mean in Java?

Tags:

java

generics

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.

like image 368
gingergeek Avatar asked Jan 14 '10 13:01

gingergeek


People also ask

What does class <?> Mean in Java?

What Does Class Mean? A class — in the context of Java — is a template used to create objects and to define object data types and methods. Classes are categories, and objects are items within each category. All class objects should have the basic class properties.

What is declared in Java?

To create a variable, you must tell Java its type and name. Creating a variable is also called declaring a variable. When you create a primitive variable Java will set aside enough bits in memory for that primitive type and associate that memory location with the name that you used.

What does this () mean in Java?

The this keyword refers to the current object in a method or constructor. The most common use of the this keyword is to eliminate the confusion between class attributes and parameters with the same name (because a class attribute is shadowed by a method or constructor parameter).

How do you declare a Java class file?

In the Project window, right-click a Java file or folder, and select New > Java Class. Alternatively, select a Java file or folder in the Project window, or click in a Java file in the Code Editor. Then select File > New > Java Class. The item you select determines the default package for the new class or type.


1 Answers

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.

like image 156
Joey Avatar answered Oct 17 '22 11:10

Joey