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?
Most likely you misunderstood what you were taught, or were taught something wrong. All variables of reference type (i.e. not primitive types) refer
directlyto an object.Creates a new instance of
Tournamentand makestest1refer to it.Copies the reference from
test1totest2, making them both refer to the same object.Makes
test1refer to a different object that has been deserialized from the stream, whiletest2still refers to the original object.