简体   繁体   English

是否可以在Java中创建泛型的2D锯齿状数组?

[英]Is it possible to create a 2D jagged array of a generic type in Java?

Is it possible to create an two-dimensional array of a generic type parameter with only a size specified in Java? 是否可以创建仅具有Java中指定大小的泛型类型参数的二维数组?

To illustrate, can we create an array like this: 为了说明,我们可以创建一个像这样的数组:

T[][] array = new T[x][];

You mention "generic" in your question and use the identifier T for your type, so I'm going to assume you are talking about creating an array of a generic type parameter. 您在问题中提到“泛型”,并为类型使用标识符T,因此,我假设您正在谈论创建泛型类型参数的数组。

You can't do that in Java. 您无法在Java中做到这一点。 Arrays and generics don't mix very well. 数组和泛型不能很好地融合在一起。 You can do it with reflection ( see this question ) but you might have an easier time doing this with a collection class instead. 您可以使用反射来做到这一点( 请参阅此问题 ),但是您可以更轻松地使用集合类来完成此操作。 It would be a List of Lists, to get a 2D ragged container. 这将是一个列表列表,以获得2D衣衫container的容器。

Not with generics, but using a known class it is possible. 不是使用泛型,而是使用已知的类是可能的。 For generic i would recommend using ArrayList or similar. 对于通用,我建议使用ArrayList或类似的东西。

 String[][] array = new String[2][];

It can be used in this way: 可以通过以下方式使用:

array[0] = new String[1];
array[1] = new String[4];
array[0][0] = "Hello 0,0";
array[1][1] = "Hello 1,1 ";

System.out.println(array[0][0]);
System.out.println(array[1][1]);

You want a generic multidimensional array. 您需要一个通用的多维数组。 You cannot create one. 您无法创建一个。 However, you can create an Object array and then cast it. 但是,您可以创建一个Object数组,然后进行转换。 This is the "usual" way of creating generic arrays: 这是创建通用数组的“常规”方法:

@SuppressWarnings("unchecked")
T[][] array = (T[][])new Object[x][];

You need @SuppressWarnings("unchecked") because the cast is not safe and checked. 您需要@SuppressWarnings("unchecked")因为@SuppressWarnings("unchecked")选中。 From a typetheoretic point of view, it is even "wrong" (an array of type Object is NOT an array of T ), but Java's type system has this inconsistency and this is the way to handle it. 从类型理论的角度来看,它甚至是“错误的”( Object类型的数组不是T的数组),但是Java的类型系统存在这种不一致,并且这是处理它的方式。

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

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