2015-01-25 4 views
2

Я получаю NullPointerException при добавлении объектов в helloArrayList. Я хочу добавить объекты по определенным индексам, поэтому, если я не добавляю 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; 
     } 


    } 

ответ

6

Когда вы пишете

hello.add(temp.get(0).x, temp.get(0)); 

вы не замените null вы кладете в индексе temp.get(0).x. Вы просто переместите это null в следующий индекс.

Таким образом, в цикле:

for(int i=0; i<4; i++) 
     Log.e("test", "i: "+i+ " index: "+hello.get(i).x); 

вы столкнулись нулевое значение, так 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)); 

для того, чтобы заменить все нулевые значения со значениями, не являющихся нулевыми.

+0

И было бы также полезно сделать вывод более надежным: «Log.e (« test »,« i: »+ i +» index: "+ (hello.get (i) == null? "": hello.get (i) .x)); ' – Koen

0

Вы можете переопределить ArrayList.set() метод для добавления объектов в определенных индексах:

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); 
    } 

} 
-4

Я думаю, вы получите сообщение об ошибке, потому что вы пытаетесь добавить более 4 элементов в список, что инициалы до 4 максимальной мощности.

+3

Первоначальная емкость - это только начальная емкость. Это * не * максимальная емкость. –

Смежные вопросы