简体   繁体   English

通用的<T extends Comparable<T> , V extends T&gt; 是 V 需要

[英]Generic <T extends Comparable<T>, V extends T> is V required

Came across this example in Java Complete Reference under Generics method.在 Java Complete Reference 中的泛型方法下遇到了这个例子。

static <T extends Comparable<T>, V extends T> boolean isIn(T x, V[] y) {
  for(int i=0; i < y.length; i++)
     if(x.equals(y[i])) return true;
        return false;
}

Here V extends T is confusing.这里V extends T令人困惑。 Can we only have <T extends Comparable<T>> to get the job done.我们能否只让<T extends Comparable<T>>来完成工作。 Because T extends some type which means the type and its sub type.因为 T 扩展了一些类型,这意味着类型及其子类型。 Then why we need V extends T?.那为什么我们需要 V 扩展 T?。 Is there any special case for using <T extends Comparable<T>, V extends T> ?使用<T extends Comparable<T>, V extends T>有什么特殊情况吗?

Yes, in this case, since the V is only used in one place, in the type of a parameter as V[] , and since array types are covariant, the V is unnecessary and the method can be written with this signature:是的,在这种情况下,由于V仅在一个地方使用,在V[]参数类型中,并且由于数组类型是协变的,因此V是不必要的,并且可以使用此签名编写该方法:

static <T extends Comparable<T>> boolean isIn(T x, T[] y)

The two method signatures would accept the same sets of arguments (assuming the caller does not specify an explicit type signature. You can see this as follows:这两个方法签名将接受相同的参数集(假设调用者没有指定显式类型签名。您可以看到如下:

  • Any argument that can be passed to the first signature as V[] can be passed to the second signature as T[] , since V extends T , so V[] extends T[] (array types in Java are covariant).任何可以作为V[]传递给第一个签名的参数都可以作为T[]传递给第二个签名,因为V extends T ,所以V[] extends T[] (Java 中的数组类型是协变的)。
  • Any argument that can be passed to the second signature as T[] can be passed to the first signature as V[] , because the compiler can always infer V as T , since T is within V 's bounds.任何可以作为T[]传递给第二个签名的参数都可以作为V[]传递给第一个签名,因为编译器总是可以将V推断为T ,因为TV的范围内。 Such an inference will not cause problems anywhere else since V is not used anywhere else.这样的推断不会在其他任何地方引起问题,因为V没有在其他任何地方使用。

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

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