views:

87

answers:

4

Hi folks. First of all I'm only aware of Java basics. Now I have the following scenario:

If 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);

The problem is, how can I define the .compareToo() Method while T is generic? I guess I have somehow to implement a constraint on the generic T to tell that T implements an specific interface (maybe Comparable, if that one exists).

Can anyone provide me with a small code sample?

+1  A: 

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

John Feminella
Gives me a compiler error.Even with such a simple TestClass:public class ConstraintTest<T implements Comparable> { }Syntax error on token "implements",, expectedWhat am I missing?
citronas
@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
Whoops. My bad, thanks for the catch, @Esko.
John Feminella
BTW, I of course meant can't above, not can.
Esko
A: 
public class ListObject<T implements Comparable> {...}
Steve Emmerson
-1 Voted down because Comparable without the type parameter is a raw type which u shouldn't use with Java 1.5+
Helper Method
+2  A: 

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
+2  A: 

Read also the discussion here: http://stackoverflow.com/questions/2071929/generics-and-sorting-in-java/2071969#2071969

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> {
    ...
}
nanda
I'll stick to ListObject<T extends Comparable> for the moment.
citronas
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