Is a deserialised object the same instance as the original

前端 未结 5 1882
心在旅途
心在旅途 2021-02-04 02:07

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

5条回答
  •  独厮守ぢ
    2021-02-04 02:25

    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).

提交回复
热议问题