Я получаю NullPointerException
при добавлении объектов в hello
ArrayList
. Я хочу добавить объекты по определенным индексам, поэтому, если я не добавляю null
объектов в массив перед началом работы, я получаю IndexOutOfBoundsException
, когда пытаюсь добавить индекс, чей предыдущий индекс еще не заселен. Почему я получаю NullPointerException
и есть ли другой способ его достижения?ArrayList 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;
}
}
И было бы также полезно сделать вывод более надежным: «Log.e (« test »,« i: »+ i +» index: "+ (hello.get (i) == null? "": hello.get (i) .x)); ' – Koen