46

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?

Rene Knop
  • 1,788
  • 3
  • 15
  • 27
citronas
  • 19,035
  • 27
  • 96
  • 164

4 Answers4

58

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> {
    ...
}
Community
  • 1
  • 1
nanda
  • 24,458
  • 13
  • 71
  • 90
  • 1
    I'll stick to ListObject for the moment. – citronas Jan 17 '10 at 16:58
  • 3
    Also check the related thread: http://stackoverflow.com/questions/2064169/what-does-this-class-declaration-mean-in-java/2072820, which discusses the need for wildcard of form: super T> – sateesh Jan 17 '10 at 17:04
5

This depends on exactly what you want the compareTo method to do. Simply defining the compareTo method to take other ListObject<T> values is done by the following

public class ListObject<T> {
  public int compareTo(ListObject<T> other) {
    ...
  }
}

However if you want to actually call methods on that parameter you'll need to add some constraints to give more information about the T value like so

class ListObject<T extends Comparable<T>> {
  ...
}
JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
3

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

John Feminella
  • 303,634
  • 46
  • 339
  • 357
  • Gives me a compiler error. Even with such a simple TestClass: public class ConstraintTest { } Syntax error on token "implements",, expected What am I missing? – citronas Jan 17 '10 at 16:45
  • @citronas: It's actually `extends` even for interfaces. Do note that if you use a base class with the `extends` attribute, you can actually add the base class directly to the generified object anymore, that's the biggest *(and worst)* side effect of the generics extension. – Esko Jan 17 '10 at 16:59
-3
public class ListObject<T implements Comparable> {...}
Steve Emmerson
  • 7,702
  • 5
  • 33
  • 59