简体   繁体   English

单个泛型参数同时接受两种不同的类型

[英]Single generic parameter accepts two different types at the same time

In the following scenario I have a method which accepts 2 arrays of Type E. It was my understanding that this E parameter means that both the arrays can be any type, but they must be the same (as I derived from this question). 在以下情况下,我有一个方法可以接受2个类型为E的数组。据我了解,此E参数意味着两个数组都可以是任何类型,但是它们必须相同(如我从这个问题得出的一样)。 I've tested this with two arrays, one Integer and one Double, but I'm not receiving any error. 我已经用两个数组进行了测试,一个是Integer,另一个是Double,但是我没有收到任何错误。 The output I receive is '14' which is the combined size of both arrays without any error thrown. 我收到的输出为'14',这是两个数组的总大小,不会引发任何错误。

Could someone shed some light as to why this works? 有人可以阐明为什么这样做有效吗?

public static <E> void showCombinedLength(E[] array1, E[] array2){
    System.out.println(array1.length + array2.length);
}

public static void main(String[] args) {
    Integer[] integerArray = {1, 2, 3, 4, 5, 6, 7};
    Double[] doubleArray = {1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7 };
    PrintArray.showCombinedLength(integerArray, doubleArray);
}

Output: 输出:

14 14

When you define a single generic type in the method definition then you can only use the method with two arrays of the same type. 当在方法定义中定义单个通用类型时,则只能将方法与两个相同类型的数组一起使用。

However, in java, array types are covariant, so both Integer[] and Double[] are subclasses of Object[] (they are also subclasses of Number[]). 但是,在Java中,数组类型是协变的,因此Integer []和Double []都是Object []的子类(它们也是Number []的子类)。 So your code will always compile, and there is no need to specify multiple type parameters. 因此,您的代码将始终进行编译,并且无需指定多个类型参数。

Your arrays are both arrays of objets. 您的数组都是objets数组。 Call it with 叫它

PrintArray.<Integer>showCombinedLength(integerArray, doubleArray);

and the compiler will refuse to compile. 并且编译器将拒绝编译。

Generics were introduced to Java in version 1.5. 泛型是在1.5版中引入Java的。 Due to the backward compability Java byte code doesn't know that some method is generic and another not. 由于向后兼容性,Java字节码不知道某些方法是通用的,而另一种则不是。 This is why after compilation your method really is: 这就是为什么在编译后您的方法实际上是:

public static void showCombinedLength(Object[] array1, Object[] array2)

All generic types are really changed to Object . 所有泛型类型实际上都已更改为Object So both Integer[] and Double[] are really arrays of objects which have length method. 因此Integer[]Double[]都是具有length方法的对象数组。 This is why this code works. 这就是为什么此代码有效的原因。

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

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