gpt4 book ai didi

来自 null 泛型类型的 Java 泛型数组

转载 作者:行者123 更新时间:2023-11-30 05:58:06 25 4
gpt4 key购买 nike

将 Array.newInstance 静态方法视为在 Java 中创建泛型类型数组的一种方法。我不知道如何从空泛型类型参数创建泛型数组:

/**
* Creates and fills a generic array with the given item
*/
public static <T> T[] create(T item, int length)
{
T[] result = (T[]) Array.newInstance(item.getClass(), length);

for(int i = 0; i < length; i++)
result[i] = item;

return result;
}

当我打电话时,上面的方法有效创建(“abc”,10);我得到一个长度为 10 的 String[],数组的所有位置都有“abc”。但是我怎样才能让一个空字符串参数返回一个长度为 10 且所有位置都为空的字符串数组呢?

例如

String nullStr = null;
String[] array = create(nullStr, 10); // boom! NullPointerException

是否有一种方法可以获取“item”类而不使用其成员之一(因为它为空)?
我知道我可以新建一个数组 String[] array = new String[10],但这不是重点。

谢谢

最佳答案

也许这很有用。

public static <T> T[] create(Class<T> clazz, int length)
{
T[] result = (T[]) Array.newInstance(clazz, length);
return result;
}

关于来自 null 泛型类型的 Java 泛型数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4764783/

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