Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why am I getting a NullPointerException with this ArrayList? [duplicate]

Tags:

java

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

Here is my arrayList AKA DynamicArray

//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 output 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)
like image 629
Ryan Miles Avatar asked Dec 13 '22 18:12

Ryan Miles


2 Answers

Confusingly, this isn't a constructor:

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

It's a function called DynamicArray (very confusing, I know).

Without the class having a constructor, data remains null and leads to an NPE when you try to access the array.

Drop the void keyword to turn the function into a constructor (which would then initialize data etc):

public DynamicArray(){
    data = new Object[1];
    size = 0;
}
like image 174
NPE Avatar answered Dec 16 '22 07:12

NPE


constructor doesn't have return value , remove return type from constructor (void)

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

in your case when you initialize object from DynamicArray class then default constructor will execute which does nothing

like image 37
Ali Faris Avatar answered Dec 16 '22 08:12

Ali Faris