gpt4 book ai didi

java - 为什么 Array.newInstance(Class, int) 不是通用的?

转载 作者:搜寻专家 更新时间:2023-10-30 20:00:08 24 4
gpt4 key购买 nike

我的意思是,这有什么好的理由吗? method有以下签名:

public static Object newInstance(Class<?> componentType,
int length)
throws NegativeArraySizeException

在我看来,将方法声明如下会更方便:

public static <T> T[] newInstance(Class<T> componentType, int length) 
throws NegativeArraySizeException

这样,在创建泛型数组时就不需要执行额外的强制转换,例如

public class Gen<T>{
private T[] a;

public static <T> Gen<T> createByClass(Class<T> clazz){
a = clazz.cast(Array.newIntance(clazz.getComponentType(), 8); //we have to invoke
//clazz.cast here.
}
}

将返回值类型声明为 Object 有什么充分的理由吗?对我来说,这似乎很不方便。

最佳答案

您可以使用 Array.newInstance(Class<?> componentType, int length)创造

  • 对象数组:Integer[] a = (Integer[])Array.newInstance(Integer.class, 5);
  • 基元数组:int[] b = (int[])Array.newInstance(int.class, 5);
  • 数组的数组:int[][] c = (int[][])Array.newInstance(b.getClass(), 5);

第二个示例说明了为什么此方法不能仅返回通用对象数组,因为基元数组不是对象数组(另一方面,数组数组是对象数组)。

使用这个辅助方法...

private static <T> T[] newArray(Class<?> type, int len){
return (T[])Array.newInstance(type, len);
}

...与int[] b = newArray(int.class, 5);会导致编译错误:

Incompatible types, required int[], but found T[]

...和 ​​int[] b = (int[])newArray(int.class, 5);会导致编译错误:

cannot cast Object[] to int[]

关于java - 为什么 Array.newInstance(Class<?>, int) 不是通用的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36053740/

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