Alex Rivera | Logout

How to set constraints on generic types in Java?

Asked 2010-01-17T16:27:51.440
49

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?

Edit
Report

1 Answer

4

Try public class ListObject<T extends U>. Only Ts which implement U (or derive from U) will be allowable substitutions.

answered 2010-01-17T16:31:33.090

Your Answer