You should override hashCode() and equals() method. you can generate these from IDE.

 @Override
public boolean equals(Object o) {
    if (this == o) return true;
    if (!(o instanceof MyData)) return false;

    MyData myData = (MyData) o;

    if (id != myData.id) return false;
    if (!desc.equals(myData.desc)) return false;
    if (!name.equals(myData.name)) return false;

    return true;
}

@Override
public int hashCode() {
    int result = id;
    result = 31 * result + name.hashCode();
    result = 31 * result + desc.hashCode();
    return result;
}

Now you can compare the objects. That's it.

Answer from Ruchira Gayan Ranaweera on Stack Overflow
🌐
Rice
clear.rice.edu › comp310 › JavaResources › RMI › compare.html
Comp310: Comparing Deserialized Objects
Object, by default, uses a direct ... instances of the same original object are compared. (The Java standard is that if two objects are equal, then they must return the same hash code.)...
Top answer
1 of 9
6

You should override hashCode() and equals() method. you can generate these from IDE.

 @Override
public boolean equals(Object o) {
    if (this == o) return true;
    if (!(o instanceof MyData)) return false;

    MyData myData = (MyData) o;

    if (id != myData.id) return false;
    if (!desc.equals(myData.desc)) return false;
    if (!name.equals(myData.name)) return false;

    return true;
}

@Override
public int hashCode() {
    int result = id;
    result = 31 * result + name.hashCode();
    result = 31 * result + desc.hashCode();
    return result;
}

Now you can compare the objects. That's it.

2 of 9
3

Conventional way is to override equals and hashCode methods. Java standard libraries, for instance Map s, List s, Set s use the equals and hashCode functions for equality testing. The code below also null-safe;

Here is the code for your case;

    public class MyData {
    int id;

    String name;

    String desc;

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        MyData myData = (MyData) o;

        if (id != myData.id) return false;
        if (desc != null ? !desc.equals(myData.desc) : myData.desc != null) return false;
        if (name != null ? !name.equals(myData.name) : myData.name != null) return false;

        return true;
    }

    @Override
    public int hashCode() {
        int result = id;
        result = 31 * result + (name != null ? name.hashCode() : 0);
        result = 31 * result + (desc != null ? desc.hashCode() : 0);
        return result;
    }
}

and you can test the equality by;

....
Mydata d1 = new...
Mydata d2 = new...
boolean areTheyEqual = d1.equals(d2);

However if you are not allowed to make a compare field by field then you can use byte arrays, there is no need to convert them to strings.

    .....
    public boolean equals(Object other){
        if (this == other) return true;
        if (other == null || getClass() != other.getClass()) return false;
        byte[] bytesThis = serialize(this);
        byte[] bytesOther = serialize(other);
        if(bytesOther.length != bytesThis.length) return false;
        return Arrays.equals(bytesThis, bytesOther);
    }

    public static byte[] serialize(Object obj) throws IOException {
        ByteArrayOutputStream b = new ByteArrayOutputStream();
        ObjectOutputStream o = new ObjectOutputStream(b);
        o.writeObject(obj);
        return b.toByteArray();
    }
    ...
Top answer
1 of 2
2

Here is a simple java object

public class MyObject {

private String firstname;
private String lastname;
private String email;

public String getFirstname() {
    return firstname;
}
public void setFirstname(String firstname) {
    this.firstname = firstname;
}
public String getLastname() {
    return lastname;
}
public void setLastname(String lastname) {
    this.lastname = lastname;
}
public String getEmail() {
    return email;
}
public void setEmail(String email) {
    this.email = email;
}

@Override
public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result
            + ((firstname == null) ? 0 : firstname.hashCode());
    result = prime * result
            + ((lastname == null) ? 0 : lastname.hashCode());
    return result;
}
@Override
public boolean equals(Object obj) {
    if (this == obj)
        return true;
    if (obj == null)
        return false;
    if (getClass() != obj.getClass())
        return false;
    MyObject other = (MyObject) obj;
    if (firstname == null) {
        if (other.firstname != null)
            return false;
    } else if (!firstname.equals(other.firstname))
        return false;
    if (lastname == null) {
        if (other.lastname != null)
            return false;
    } else if (!lastname.equals(other.lastname))
        return false;
    return true;
}
}

(hashcode and equals auto generated by eclipse)

If you look at equals() method, you will see that 2 objects are compared on the fields firstname and lastname, and only those 2. This means that if you insert objects of this type in a list, you will be able to use contains(Object o) and if an object contains the same firstname and lastname, you'll find it.

2 of 2
1

You need to override the equals and hashcode method of your object (many examples are available on SO, for example here.

Once you have done that, the contains method of List will behave as you expect. Your problem does not seem related to serialization. In other words, the following code:

List<MyObject> list = new ArrayList<MyObject>();
list.add(new MyObject());
System.out.println(list.contains(new MyObject()));

will print false if you don't override equals & hashcode whereas it might print true if you do (depending on whether your equals method consider those 2 new MyObject() to be equals or not). Your IDE should have a way to auto generate the code for you.

Once you are happy that the contains method works as expected on your objects, serialising/deserialising should work as expected.

🌐
Stack Overflow
stackoverflow.com › questions › 28307484 › how-to-compare-diff-two-objects-in-java
json - How to compare / diff two objects in java - Stack Overflow
I always and only need to compare two objects. I am wondering that is there any existing library for doing that ? or is there any suggestion for doing that ? ... Then you must use an external comparator. docs.oracle.com/javase/8/docs/api/java/util/Comparator.html
🌐
InfoWorld
infoworld.com › home › software development
Object equality | InfoWorld
August 22, 2019 - The reason why static fields are not compared is because they are the same for all class instances and thus clearly identical in an instance-based comparison. transient fields are not compared because the transient keyword’s purpose is to prevent fields from being written during serialization; and these fields should therefore not play a part in equality testing. Otherwise, if an object is serialized and then de-serialized, then it will not be equal to itself.
🌐
ResearchGate
researchgate.net › publication › 234812425_Object_serialization_analysis_and_comparison_in_Java_and_NET
Object serialization analysis and comparison in Java and .NET | Request PDF
August 1, 2003 - It uses three different types of ... of objects to make a comparison which reflects real-world circumstances. The article has the following contributions: (1) it compares binary and XML serialization between Java and .NET to compare the efficiency of both platforms; (2) it compares binary and XML serialization within the platforms to compare the differences between the two serialization ...
Find elsewhere
🌐
CodeGym
codegym.cc › java blog › serialization in java › what is the difference between serialization and deserial...
What is the difference between serialization and deserialization in Java?
May 25, 2023 - Exception in thread "main" java.io.NotSerializableException: DiplomacyInfo It didn't work! Basically, that's the answer to our question. When an object is serialized, all of the objects referenced by its instance variables are serialized. And if those objects also reference other objects, then they are also serialized.
🌐
Hazelcast
hazelcast.com › home › comparing serialization options
Comparing Serialization Options | Hazelcast
May 26, 2021 - The score column tells us for the 100,000 objects, java.io.Serializable takes 33 seconds to serialize and 11 to deserialize.
🌐
HappyCoders
happycoders.eu › home › java › serialization in java: serializable, transient, serialversionuid
Serialization in Java: Serializable, transient, serialVersionUID
5 days ago - For each class, an object stream contains a version number, the serialVersionUID. When reading, ObjectInputStream compares it with the serialVersionUID of the class that is currently on the classpath. If the two differ, it throws an ...
🌐
Baeldung
baeldung.com › home › json › jackson › compare two json objects with jackson
Compare Two JSON Objects with Jackson | Baeldung
January 8, 2024 - Learn how to use Jackson to compare two JSON objects using the built-in comparator and a custom comparator
🌐
HappyCoders
happycoders.eu › home › java › compareto, comparable, comparator – comparing objects in java
compareTo, Comparable, Comparator – Compare Objects in Java
September 19, 2026 - The accessor methods are then called id(), firstName(), and lastName(), and you write the comparator chains further below as Comparator.comparing(Student::lastName). Let’s get back to the String that we want to sort by length, not alphabetically. ... Get the compact overview of all Java versions. You’ll instantly know which updates are worth adopting in your project – and see at a glance which Java version introduced a specific feature. You get access to this PDF collection by signing up for my newsletter. You can opt-out at any time. To sort two objects by an order other than their natural order (or to sort objects of classes that do not implement Comparable at all), we have to use the java.util.Comparator interface.
🌐
Javers
javers.org › documentation › diff-examples
Diff Examples — JaVers Documentation
These objects represent two different addresses. To find out what the difference is, just call: ... What’s important When JaVers knows nothing about a class, it treats it as Value Object. As we said in the previous example, JaVers compares only objects with the same GlobalId.
🌐
Quora
quora.com › How-do-I-compare-two-JSON-which-has-different-structures-using-Java
How to compare two JSON which has different structures using Java - Quora
Answer (1 of 2): You may try implementing this logic - 1. Consider each JSON object as a set. 2. And each key and value of the object defines a member of the set. Offcourse the value of a member of this set can be a key and another set. 3. Apply set difference on both of the sets. And two member...
🌐
Oracle
docs.oracle.com › javase › 8 › docs › platform › serialization › spec › version.html
Java Object Serialization Specification: 5 - Versioning of Serializable Objects
April 21, 2026 - All data and objects must be read from, or skipped in, the stream in the same order as they were written. Classes evolve individually as well as in concert with supertypes and subtypes. Classes are identified by name. Two classes with the same name may be different versions or completely different classes that can be distinguished only by comparing their interfaces or by comparing hashes of the interfaces. Default serialization will not perform any type conversions.