简体   繁体   中英

NullPointerException when trying to set an element in a multidimensional ArrayList

I am having a hard time figuring how to add objects to an ArrayList of ArrayList.

When I try:

ArrayList<ArrayList<A>> matrix = new ArrayList<ArrayList<A>>();

matrix.add(new ArrayList<A>());
matrix.add(new ArrayList<A>());
matrix.add(new ArrayList<A>());

matrix.get(0).set(0, A);

I get a NullPointerException.

What am I doing wrong?

You are setting at position not present in arraylist, may be you need "add".

import java.util.ArrayList;

class A{}

public class arrlst {

    public static void main(String[] args) {
        ArrayList<ArrayList<A>> matrix = new ArrayList<ArrayList<A>>();

        matrix.add(new ArrayList<A>());
        matrix.add(new ArrayList<A>());
        matrix.add(new ArrayList<A>());

        /*matrix.get(0).set(1, new A());*/
        matrix.get(0).add(new A());

    }

}

Also you need to create object of class A, you can't set A.

I guess you might be getting java.lang.IndexOutOfBoundsException . And that is because after matrix.add(new ArrayList<A>()); newly added ArrayList's Size is 0. set method initially check the size of the AraayList before setting the element at the mentioned position.

public E set(int paramInt, E paramE) { RangeCheck(paramInt); Object localObject = this.elementData[paramInt]; this.elementData[paramInt] = paramE; return localObject; }

private void RangeCheck(int paramInt) { if (paramInt < this.size) return; throw new IndexOutOfBoundsException("Index: " + paramInt + ", Size: " + this.size); }

As newly added ArrayList has Size as 0, java.lang.IndexOutOfBoundsException is thrown.

So, before setting the element make sure you the elements to the ArrayList using add method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM