2

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


    }

3 Answers 3

6

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.

Sign up to request clarification or add additional context in comments.

1 Comment

And it would also be helpful to make the output more robust, like this: Log.e("test", "i: "+i+ " index: "+(hello.get(i)==null ? "" : hello.get(i).x));
0

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

}

Comments

-4

I think you get the error because you try to add more then 4 elements to the list that initials to 4 maximum capacity.

1 Comment

The initial capacity is just that, an initial capacity. It is not a maximum capacity.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.