Reputation: 151
I have a object which contains an array of doubles.
public class NumberRow {
static final int MAX_AMOUNT_OF_NUMBERS = 2500;
double[] NumberArray = new double[MAX_AMOUNT_OF_NUMBERS];
NumberRow(double[] NumberArray){
this.NumberArray = NumberArray;
}
}
In my main program I start with creating a array of the object NumberRow in the constructor like this
NumberRow[] numberRow;
later in the program I put this code:
numberRow = new NumberRow[dataset.numberOfVariables];
After that I call a function which gives value to an numberRow:
double misc = in.nextDouble();
numberRow[k].NumberArray[i] = misc;
I did say where NumberRow is pointing to. However, eclipse gives me a null pointer pointer exception on this line:
numberRow[k].NumberArray[i] = misc;
I hope anyone can see what I did wrong? Thank you :)!
Upvotes: 1
Views: 97
Reputation: 1988
This is a common mistake I see when beginners start to use arrays of objects. When an array of object references is created, the array is initialized, but the individual elements in the array are null
. So, on the statement numberRow[k].NumberArray[i] = misc;
, numberRow[k]
is null
, which is causing the exception. Therefore, before the line, you need to put the statement
numberRow[k] = new NumberRow();
before the above statement.
Upvotes: 1
Reputation: 21773
When you do this:
numberRow = new NumberRow[dataset.numberOfVariables];
All of the members of the array numberRow
are initialized to the default value of NumberRow
. NumberRow
is a class, therefore its default value is null. To set values on something that is null, you must first initialize it to a new
, real object or you will get a NullPointerException.
Upvotes: 1