When I instantiate an object from a class, an object is saved in the java heap. When I save the object by serializing it and I later deserialize the object, do I understand corr
The deserialized instance will definitely be a distinct instance from the original, as in deserialized != original
will always be true.
The deserialized instance may or may not be equal to the original instance, as in deserialized.equals(original)
. For a reasonable implementation of a Serializable
class, equals
probably will be true after deserialization, but it is trivial to create a class for which this does not hold:
class Pathological implements Serializable {
transient int value;
Pathological(int value) { this.value = value; }
@Override public int hashCode() { return value; }
@Override public boolean equals(Object other) {
if (other == this) { return true; }
if (other instanceof Pathological) {
return ((Pathological) other).value == this.value;
}
return false;
}
}
Unless you happen to pass zero when constructing the Pathological
, the instances won't be equal after serialization/deserialization, since the value of value
won't be serialized (as it is transient).