Question

When working on a program for school, I created a method which returned the index of an array based on the value you gave the method. The method throws a NullPointerException but in every index of the array has already been instantiated. To show this, I created a test program which does the same thing.

public class Test {
private static Number[] numbers = new Number[16];

public static void main(String[] args) {
    new Test();
}

public Test() {
    for (Number n : numbers) {
        n = new Number(0);
    }
    System.out.println(get(0).value);
}

public Number get(int index) {
    return numbers[index];
}

class Number {
    public int value;

    public Number(int value) {
        this.value = value;
        }
    }
}

When run this should print the value of the Integer "value", in this case of the object in the first position of the array.

I am sure there is a simple explanation to this, but I am unaware of the problem.

Was it helpful?

Solution

You have to use the for-each loop for read-only passes. Currently, in your constructor, the elements in your array still remain uninitialized and hence the error.

So change it to a normal for loop.

for(int i = 0; i < numbers.length; i++){
    numbers[i] = new Number(0);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top