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?
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.
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.
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.
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).
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> { ... }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With