Reputation: 3012
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;
}
}
Upvotes: 2
Views: 1079
Reputation: 96
I think you get the error because you try to add more then 4 elements to the list that initials to 4 maximum capacity.
Upvotes: -4
Reputation: 4584
You can override ArrayList.set()
method to add objects at specific indexes:
public class SparseArrayList<E> extends ArrayList<E> {
@Override
public E set(int index, E element) {
while (size() <= index) add(null);
return super.set(index, element);
}
}
Upvotes: 0
Reputation: 394146
When you write
hello.add(temp.get(0).x, temp.get(0));
you don't replace the null
you put in the temp.get(0).x
index. You just move that null
to the next index.
Therefore, in the loop :
for(int i=0; i<4; i++)
Log.e("test", "i: "+i+ " index: "+hello.get(i).x);
you encounter a null value, so hello.get(i).x
throws NullPointerException
.
change it to
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));
in order to replace all the null values with non null values.
Upvotes: 6