gpt4 book ai didi

java - 如何在 Java 中创建类型变量数组?

转载 作者:搜寻专家 更新时间:2023-11-01 01:23:47 25 4
gpt4 key购买 nike

在 Java 中可以声明类型变量数组,但我无法创建数组。不可能吗?

class ClassName<T> {
{
T[] localVar; // OK
localVar = new T[3]; // Error: Cannot create a generic array of T
}
}

最佳答案

Java 中没有通用类型的数组。你可以去 ArrayList

解释:

java中的数组是协变类型。

Java arrays have the property that there types are covariant , which means that an array of supertype references is a supertype of an array of subtype references.That is, Object[] is a supertype of String[] for example. As a result of covariance all the type rules apply that are customary for sub- and supertypes: a subtype array can be assigned to a supertype array variable, subtype arrays can be passed as arguments to methods that expect supertype arrays, and so on and so forth.Here is an example:

Object[] objArr = new String[10];// fine

In contrast, generic collections are not covariant. An instantiation of a parameterized type for a supertype is not considered a supertype of an instantiation of the same parameterized type for a subtype.That is, a LinkedList<Object> is not a super type of LinkedList<String> and consequently a LinkedList<String> cannot be used where a LinkedList<Object> is expected; there is no assignment compatibility between those two instantiations of the same parameterized type, etc.Here is an example that illustrates the difference:

LinkedList<Object> objLst = new LinkedList<String>(); // compile-time error

来源:http://www.angelikalanger.com/Articles/Papers/JavaGenerics/ArraysInJavaGenerics.htm

关于java - 如何在 Java 中创建类型变量数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4738837/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com