java 泛型 类型约束,如何在Java中对泛型类型设置约束?

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

I have a generic class:

public class ListObject

{

// fields

protected T _Value = null;

// ..

}

Now I want to do something like the following:

ListObject foo = new ListObject();

ListObject foo2 = new ListObject();

foo.compareTo(foo2);

The problem is, how can I define the .compareTo() 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?

解决方案

Read also the discussion here: Generics and sorting in Java

Short answer, the best you can get is:

class ListObject> {

...

}

But there is also reason to just use:

class ListObject {

...

}

你可能感兴趣的:(java,泛型,类型约束)