user1547050
user1547050

Reputation: 337

NullPointerException when creating an ArrayList-like class

As a practice exercise, I am creating my own generic class that is basically a copy of ArrayList. While testing the class with JUnit, I come across a NullPointerException error in the add method:

public void add(int index, T element) {
    if (index > this.size() || index < 0) {
        throw new IndexOutOfBoundsException();
    }

    if (this.size() == data.length) {
        // ^ This is the line that the error points to
        resize(this.data);
    }

    for (int i = index; i < this.size; i++) {
        this.data[i + 1] = this.data[i]; //fix
    }

    this.data[index] = element;
    size++;
}

After messing around with the class a lot, I can't figure out where the error is coming from. I can provide any details/other parts of the class that are needed. Any guidance as to where the problem is located would be fantastic. Thank You.

The constructor for the class:

MyArrayList(int startSize) {
    // round the startSize to nearest power of 2
    int pow2 = 1;
    do {
        pow2 *= 2;
    } while (pow2 < startSize);

    startSize = pow2;
    this.size = 0;
    T[] data = (T[]) new Object[startSize];
}

The following test case tests the size, but encounters the error when it tries to add an element:

public void testSize() {
    MyArrayList<Integer> test = new MyArrayList<Integer>(); 
    ArrayList<Integer> real = new ArrayList<Integer>();
    assertEquals("Size after construction", real.size(), test.size());
    test.add(0,5);
    real.add(0,5);
    assertEquals("Size after add", real.size(), test.size());
}

Upvotes: 1

Views: 235

Answers (2)

basiljames
basiljames

Reputation: 4847

I the NPE is on the line you have mentioned it is only because data is null. Where are you initialyzing data ?

Maybe when you are creating your CustomArrayList you are not initialyzing your internal array data.

The data intialisation is the problem. It should be
this.data = (T[])new Object[startSize];

Upvotes: 0

Bhesh Gurung
Bhesh Gurung

Reputation: 51030

T[] data = (T[]) new Object[startSize];

That initializes the local variable data. Which you don't want.

Change it to following to make sure that you initialize the instance variable -

this.data = (T[]) new Object[startSize];

Upvotes: 6

Related Questions