Reputation: 622
I have the following class, which performs some calculations to fill its static arrays.
public class Amount implements Serializable{
private static final long serialVersionUID = 8141477444408242243L;
public static Amount values1[][] = new Amount[10][30];
public static Amount values2[][] = new Amount[10][30];
public static Amount values3[][] = new Amount[10][30];
double highestValue;
double highestAmount;
double lowestAmount;
double lowestValue;
...
}
As the calculations take 20 minutes or so, I am looking to store the arrays on file and load the values when the program starts. I am attempting to use the java serialization method and have the following functions
public static void loadFile(Amount[][] arr, String filename){
try {
FileInputStream fis = new FileInputStream(filename);
ObjectInputStream in = new ObjectInputStream(fis);
arr = (Amount[][])in.readObject();
in.close();
}
catch (Exception e) {
System.out.println(e);
}
}
public static void saveFile(Amount[][] arr, String filename){
try {
FileOutputStream fos = new FileOutputStream(filename);
ObjectOutputStream out = new ObjectOutputStream(fos);
out.writeObject(arr);
out.flush();
out.close();
}
catch (IOException e) {
System.out.println(e);
}
}
which I call like this saveFile(values1, "valueOneSaveFile");
and loadFile(values1, "valueOneSaveFile");
I have run the program once, saving all the arrays to various files. The files have been created and look to be around the correct size. When I change my program to call the loadFile functions, the arrays do not appear to initialize correctly. I am getting null pointer exceptions when trying to read a value from the array (which appears to be empty after the load)
Upvotes: 1
Views: 12378
Reputation: 1802
The problem is in your LoadFile method. Java passes parameters by value. In the case of objects a copy of the "pointer" is passed. When you update the array:
arr = (Amount[][])in.readObject();
You are not updating Amount.values1 array, instead the local arr variable points to a new array.
You should change the method signature to:
public static Amount[][] loadFile(String filename)
And use it accordingly.
Upvotes: 3