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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2081663/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 03:20:16  来源:igfitidea点击:

How to set constraints on generic types in Java?

javagenericsconstraints

提问by citronas

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?

如何定义compareTo()与泛型相关的方法T

I guess I have to somehow implement a constraint on the generic T, to tell that Timplements a specific interface (maybe Comparable, if that one exists).

我想我必须以某种方式在 generic 上实现一个约束T,以告诉它T实现了一个特定的接口(也许Comparable,如果存在的话)。

Can anyone provide me with a small code sample?

谁能给我提供一个小的代码示例?

采纳答案by nanda

Read also the discussion here: Generics and sorting in Java

另请阅读此处的讨论: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> {
    ...
}

回答by John Feminella

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

试试public class ListObject<T extends U>。只有T实现U(或派生自U)的s才是允许的替换。

回答by Steve Emmerson

public class ListObject<T implements Comparable> {...}

回答by JaredPar

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

这完全取决于您希望 compareTo 方法做什么。简单地定义 compareTo 方法以采用其他ListObject<T>值是通过以下方式完成的

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 Tvalue like so

但是,如果您想实际调用该参数的方法,则需要添加一些约束以提供有关该T值的更多信息,如下所示

class ListObject<T extends Comparable<T>> {
  ...
}