Variable reference problem when loading an object from a file in Java
- by Snail
I have a problem with the reference of a variable when loading a saved serialized object from a data file. All the variables referencing to the same object doesn't seem to update on the change. I've made a code snipped below that illustrates the problem.
Tournament test1 = new Tournament();
Tournament test2 = test1;
try {
FileInputStream fis = new FileInputStream("test.out");
ObjectInputStream in = new ObjectInputStream(fis);
test1 = (Tournament) in.readObject();
in.close();
}
catch (IOException ex){
Logger.getLogger(Frame.class.getName()).log(Level.SEVERE, null, ex);
}
catch (ClassNotFoundException ex){
Logger.getLogger(Frame.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println("test1: " + test1);
System.out.println("test2: " + test2);
After this code is ran test1 and test2 doesn't reference to the same object anymore. To my knowledge they should do that since in the declaration of test2 makes it a reference to test1. When test1 is updated test2 should reflect the change and return the new object when called in the code. Am I missing something essential here or have I been misstaught about how the variable references in Java works?