Variable reference problem when loading an object from a file in Java
Posted
by Snail
on Stack Overflow
See other posts from Stack Overflow
or by Snail
Published on 2010-04-15T16:58:29Z
Indexed on
2010/04/15
17:03 UTC
Read the original article
Hit count: 292
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?
© Stack Overflow or respective owner