@SafeVarargs
确实已经为解决方案提供了一个线索.将该方法设置为varargs方法.由于可变数量的参数也允许零参数,因此此更改允许不变的调用:
public class Example
{
@SafeVarargs
static <T> T[] construct(int size, T... template) {
return Arrays.copyOf(template, size);
}
public static void main(String args[])
{
List<String>[] result = Example.<List<String>>construct(10);
System.out.println(result.getClass().getComponentType());
}
}
请注意,这里不需要显式类型参数.呼叫者可以简化为
List<String>[] result = Example.construct(10);
这意味着当我们在同一个类中或使用imp或t static …
时,我们甚至可以省略声明类
List<String>[] result = construct(10);
但是,当调用方向varargs参数提供实参时,它们可能会出现在结果数组中.要强制使用只有null
个元素的数组,可以使用
@SafeVarargs
static <T> T[] construct(int size, T... template) {
return Arrays.copyOf(Arrays.copyOf(template, 0), size);
}
或
@SafeVarargs
static <T> T[] construct(int size, T... template) {
T[] array = Arrays.copyOf(template, size);
Arrays.fill(array, null);
return array;
}
可以使用以下工具进行测试
List<String>[] result = construct(10, Collections.emptyList());
System.out.println(result.getClass().getComponentType());
System.out.println(Arrays.toString(result));
But note that the creation of generic arrays is not allowed f或 a reason. Consider
List<String>[] result = construct(10);
Object[] array = result;
array[0] = Arrays.asList(42);
List<String> stringList = result[0];
// this situation is called heap pollution
// at an entirely different place in you application, you might do
String s = stringList.get(0);
// without understanding what's going on