Why am I getting a NullPointerException with this ArrayList?

When I add an object to this ArrayList, my resize method gives me a NullPointerException. The list is initialized with size 1, and the first element is added to size 0 in the array.

Here is my List AKA DynamicArray array

//Implementation of a dynamic array
// Add remove methods


public class DynamicArray {
    private Object[] data;
    private int size;

public void DynamicArray(){
    data = new Object[1];
    size = 0;
}

public int size(){return size;}

public Object get(int index){return data[index];};

private void resizeIfFull()
{
    if (size < data.length){
        return;
        } else {
            Object[] bigger = new Object[2 * data.length];
            for (int i = 0; i < data.length; i++){
                bigger[i] = data[i];
                data = bigger;
        }
    }
}

public void add(Object obj){
    resizeIfFull();
    data[size] = obj;
    size++;
}

public void add(int index, Object obj){
    resizeIfFull(); 
    for(int i = size - 1; i >= index; i--){
        data[i+1] = data[i];
    }
    data[index] = obj;
    size++;
}

public void remove(int index){
    for(int i = index; i < size; i++){
        data[i] = data[i+1];
    }
    size--;
}

}

Here is my testing class.

public class AlgorTest {

public static void main(String[] args) {
    // TODO Auto-generated method stub
    DynamicArray dynam = new DynamicArray();
    System.out.println(dynam.size());
    dynam.add("first");

}

}

Here is my conclusion from the testing class.

0
Exception in thread "main" java.lang.NullPointerException
at DynamicArray.resizeIfFull(DynamicArray.java:20)
at DynamicArray.add(DynamicArray.java:38)
at AlgorTest.main(AlgorTest.java:8)
+4
source share
2 answers

Vaguely, this is not a constructor:

public void DynamicArray(){
    data = new Object[1];
    size = 0;
}

This is a feature called DynamicArray(very confusing, I know).

Without a class having a constructor, it dataremains nulland leads to NPE when trying to access the array.

void, ( data ..):

public DynamicArray(){
    data = new Object[1];
    size = 0;
}
+6

, (void)

public DynamicArray(){
    data = new Object[1];
    size = 0;
}

, DynamicArray, ,

+6

Source: https://habr.com/ru/post/1692716/


All Articles