Cheta Andrei
Cheta Andrei

Reputation: 1

Why two object are not equals after i save with serializable

public class ProveSerialization {
    public static void main(String[] args) throws Exception{
    
        Save obj = new Save();
        obj.a = 4;

        File f = new File("File.txt");
        FileOutputStream fos = new FileOutputStream(f);
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        oos.writeObject(obj);

        FileInputStream fis = new FileInputStream(f);
        ObjectInputStream ois = new ObjectInputStream(fis);
        Save obj1 = (Save) ois.readObject();

        System.out.println(obj1.a);
        System.out.println(obj);
        System.out.println(obj1);
        System.out.println(obj.equals(obj1));
        System.out.println(obj == obj1);

Output:

4
Save@14ae5a5
Save@6d03e736
false
false

Upvotes: 0

Views: 68

Answers (1)

Nikolas
Nikolas

Reputation: 2410

Check the implementation of equals in the Object class; it compares the identity of two objects, which can only be true if the two objects occupy the very same space in memory. However, by serializing your object, you effectively create a new one (which is fine, as you might even intent to exchange your serialized object between two VMs. As a result, a serialized object can never be the same as it was before.

However, if you intend to loosen the definition of equals for your Save object, keep in mind that you could override the method. But I guess, that is OT, right?

Upvotes: 1

Related Questions