Sobes.tech
Junior — Middle

Objects that have undergone serialization and subsequent deserialization will they maintain equality according to the equals() method?

sobes.tech AI

Answer from AI

Objects that have undergone serialization and subsequent deserialization do not guarantee the preservation of equality according to the equals() method unless this method is specifically overridden to compare the contents of objects. By default, the equals() method in Java (and Android) compares object references, and after deserialization, a new object with a different memory address is created.

If the class correctly overrides equals() and compares internal fields, then objects before and after serialization can be considered equal. Otherwise, they are not.

Example:

class Person implements Serializable {
    String name;
    int age;

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Person person = (Person) o;
        return age == person.age && Objects.equals(name, person.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, age);
    }
}

In this case, after deserialization, objects with the same field values will be equal according to equals().

Objects that have undergone serialization and… - sobes.tech