简体   繁体   English

Java泛型说明(使用Comparable时,将T约束为一个类型)

[英]Java Generics Clarification( Constraining T to a type, while using Comparable)

If I were to create a class and that class is intended to only accept a specific type of data. 如果我要创建一个类,并且该类仅接受特定类型的数据。 I would proceed to use generics and in this class I will proceed to have the type constrained to the upper bound of the Number class. 我将继续使用泛型,并且在该类中,我将把类型限制为Number类的上限。

So this class can only use types of the Number class or the subclasses of Number (Integer, Double, Long, etc). 因此,此类只能使用Number类的类型或Number的子类(Integer,Double,Long等)。

Lets now say I have an array of these types and I wish to compare values in that array. 现在说我有一个这些类型的数组,我希望比较该数组中的值。 So this class contains an array of only these allowed data types, and we wish to compare these types only. 因此,此类仅包含这些允许的数据类型的数组,并且我们仅希望比较这些类型。

We can do this by using the comparable interface which contains the compareTo method. 我们可以使用包含compareTo方法的可比较接口来做到这一点。 You can only use the compareTo method with classes that implement the Comparable interface. 您只能将compareTo方法与实现Comparable接口的类一起使用。 Number is one of the classes that implement this interface. Number是实现此接口的类之一。

So If I have a class header that specifies the following: 因此,如果我有一个指定以下内容的类头:

public class SomeName<T extends Number> {

This successfully implies the constraint of the type T to only accept types of Number or subclasses of number. 这成功暗示了类型T的约束,使其仅接受Number类型或number的子类。 If I wanted to use the compareTo method from the Comparable interface, which Numbers class implements, which T is constrained to. 如果我想使用Comparable接口中的compareTo方法,则Numbers类要实现,而T则要约束到该方法。

If I were to have a method such as 如果我要使用诸如

public T someName(T[] SomeVariable) {

Why can't that method use the compareTo method?T is constrainted to the Number class, which implements Comparable. 为什么该方法不能使用compareTo方法?T被限制在实现Comparable的Number类上。

If I were to have 如果我有

 public <T extends Comparable<T>> someName(T[] SomeVariable) {

Then it works because T extends comparable, which is the samething as T implements comparable in generic notation... Isn't that practically the same thing as above though? 然后它就起作用了,因为T扩展了可比性,这与T所实现的可比性在通用表示法中是可比的...难道实际上不是与上述相同吗?

Number does not implement Comparable . Number 实现Comparable

The thing to use is: 使用的是:

SomeName<T extends Number & Comparable<? super T>>

At present, you cannot impose extra restrictions on T in an instance method, so if you write 目前,您无法在实例方法中对T施加额外的限制,因此如果您编写

public <T extends Comparable<T>> T someName(T[] SomeVariable)

that's actually a different T . 这实际上是一个不同的T

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM