Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set constraints on generic types in Java?

I have a generic class:

public class ListObject<T> {     // fields     protected T _Value = null;       // .. } 

Now I want to do something like the following:

ListObject<MyClass> foo = new ListObject<MyClass>(); ListObject<MyClass> foo2 = new ListObject<MyClass>(); foo.compareTo(foo2); 

Question:

How can I define the compareTo() method with resprect to the generic T?

I guess I have to somehow implement a constraint on the generic T, to tell that T implements a specific interface (maybe Comparable, if that one exists).

Can anyone provide me with a small code sample?

like image 437
citronas Avatar asked Jan 17 '10 16:01

citronas


People also ask

How do I restrict a generic type in Java?

Java For Testers Whenever you want to restrict the type parameter to subtypes of a particular class you can use the bounded type parameter. If you just specify a type (class) as bounded parameter, only sub types of that particular class are accepted by the current generic class.

How do you add generic constraints?

You can specify one or more constraints on the generic type using the where clause after the generic type name. The following example demonstrates a generic class with a constraint to reference types when instantiating the generic class.

Can generic classes be constrained?

Declaring those constraints means you can use the operations and method calls of the constraining type. If your generic class or method uses any operation on the generic members beyond simple assignment or calling any methods not supported by System. Object, you'll apply constraints to the type parameter.

How do you declare a generic bounded type parameter in Java?

To declare a bounded type parameter, list the type parameter's name, followed by the extends keyword, followed by its upper bound, which in this example is Number . Note that, in this context, extends is used in a general sense to mean either "extends" (as in classes) or "implements" (as in interfaces).


1 Answers

Read also the discussion here: Generics and sorting in Java

Short answer, the best you can get is:

class ListObject<T extends Comparable<? super T>> {     ... } 

But there is also reason to just use:

class ListObject<T extends Comparable> {     ... } 
like image 79
nanda Avatar answered Oct 02 '22 13:10

nanda