将对象添加到 hello
ArrayList
时遇到 NullPointerException
。我想在特定索引处添加对象,因此如果我事先没有将 null
对象添加到数组中,当我尝试在以下索引处添加对象时,我会收到 IndexOutOfBoundsException
:之前的索引尚未填充。为什么我会收到 NullPointerException
以及是否有其他方法可以实现它?
public void test()
{
ArrayList<TEST> temp = new ArrayList<>(4);
temp.add(0,new TEST(2));
temp.add(1,new TEST(3));
temp.add(2,new TEST(1));
temp.add(3,new TEST(0));
for(int i=0; i<4; i++)
Log.e("test", "i: "+i+ " index: "+temp.get(i).x);
ArrayList<TEST> hello = new ArrayList<>(4);
hello.add(null);
hello.add(null);
hello.add(null);
hello.add(null);
hello.add(temp.get(0).x, temp.get(0));
hello.add(temp.get(1).x, temp.get(1));
hello.add(temp.get(2).x, temp.get(2));
hello.add(temp.get(3).x, temp.get(3));
Log.e("test", "___________________________");
for(int i=0; i<4; i++)
Log.e("test", "i: "+i+ " index: "+hello.get(i).x);
}
public class TEST
{
int x;
public TEST(int x) {
this.x = x;
}
}
最佳答案
当你写的时候
hello.add(temp.get(0).x, temp.get(0));
您不会替换放入 temp.get(0).x
索引中的 null
。您只需将该 null
移动到下一个索引即可。
因此,在循环中:
for(int i=0; i<4; i++)
Log.e("test", "i: "+i+ " index: "+hello.get(i).x);
您遇到 null 值,因此 hello.get(i).x
抛出 NullPointerException
。
修改为
hello.set(temp.get(0).x, temp.get(0));
hello.set(temp.get(1).x, temp.get(1));
hello.set(temp.get(2).x, temp.get(2));
hello.set(temp.get(3).x, temp.get(3));
以便用非空值替换所有空值。
关于java - ArrayList 空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28134453/