I am getting a NullPointerException while adding objects to hello ArrayList. I want to add objects at specific indices, so if I don't add null objects to the array before hand, I get IndexOutOfBoundsException when I try to add at an index whose previous index hasn't been populated yet. Why am I getting a NullPointerException and is there any other way to achieve it?
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;
}
}