I try to create a program to compare 2 objects. If I create 2 instances of the same object, the 2 objects are differents because, even if they have the same "tin", they are 2 individuals objects.
But, in my case, I create an object, serialize it, deserialize it into a second instance and compare the original with the copy.
Why are they different ? I don't even use "new" to create the second instance. I just read the serialized object... Here are the 2 classes I use :
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class Main {
public static void main(String[] args) {
File file = new File("something.serial");
//Creation of the 1st object
Something obj1 = new Something();
//Serialization
ObjectOutputStream oos;
try {
oos= new ObjectOutputStream(
new BufferedOutputStream(
new FileOutputStream(file)));
oos.writeObject(obj1);
oos.close();
} catch (IOException e) {
e.printStackTrace();
}
//Second object
Something obj2=null;
//Deserialization
ObjectInputStream ois;
try {
BufferedInputStream bis = new BufferedInputStream(
new FileInputStream(file));
ois = new ObjectInputStream(bis);
obj2=(Something)ois.readObject();
ois.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
//Compare
if (obj1.equals(obj2)) {
System.out.println("Same");
} else {
System.out.println("Different : ");
System.out.println(obj1.toString()+" - "+obj2.toString());
}
}
}
and :
import java.io.Serializable;
public class Something implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
public int value = 2;
Something () {
}
}
Thank you for all your answers that will help me to understand.