gpt4 book ai didi

Java 通用列表 - 使用 Array.newInstance 导致 Nullpointer

转载 作者:行者123 更新时间:2023-12-01 19:33:12 26 4
gpt4 key购买 nike

我目前正在尝试使用通用列表来为一个构造函数类使用不同的数据类型(int、double、string 等)。当我尝试创建数组时遇到问题。我正在使用以下代码:

import java.lang.reflect.Array;

public class SimpleArrayList<ListedType> extends entrance {
private int length;
private int grow;
private ListedType[] buffer;


@SuppressWarnings("unchecked")
public SimpleArrayList(int InitialLength,int grow){
length= 0;
this.grow = grow;
buffer = (ListedType[])Array.newInstance(getClass().getComponentType(),InitialLength);
}

使用以下测试 field :

public class entrance {

public static void main(String[] args) {
SimpleArrayList<?> A = new SimpleArrayList<Integer>(10,1);

for (int i=0; i<=A.getLength()-1; i++)
System.out.print(A.getAt(i)+ ", ");
}

}

有人可以帮我吗?

最佳答案

问题是您对 getClass().getComponentType() 的调用。 getClass() 方法将返回 SimpleArrayList.class,然后 getComponentType() 将返回 null,因为 SimpleArrayList 不是数组。

简短的例子:

public class Test {    
public static void main(String[] args) {
new Foo<String>().printComponentType();
}
}

class Foo<T> {
public void printComponentType() {
System.out.println(getClass().getComponentType()); // null
}
}
如果您传递 null 作为第一个参数,

Array.newInstance 会抛出 NullPointerException

关于Java 通用列表 - 使用 Array.newInstance 导致 Nullpointer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58889437/

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