How to implement equals method for class contains another class in java

40 views Asked by At

I want to compare StudentDTO class object.

  StudentDTO s1 = new StudentDTO();
      StudentDTO s2 = new StudentDTO();
      s1.equals(s2)

I have Class StudentDTO contains AddressDTO class object as variable and name as String.

StudentDTO 
      --> String name 
      --> AddressDTO 

I am aware of how to implement equals method with datatypes. But now i want to implement hashcode and equals method for StudentDTO class containing AddressDTO class.

@Data
public class StudentDTO {
               public AddressDTO address;
               public String name;
}

Appreciate your help.

1

There are 1 answers

0
Mustafa Abudalu On

If you have another class then you need to also override the equal and the hashcode of the inner class and call the equal method for it in studentdto class, do the following

Step 1: Implement equals and hashCode in AddressDTO

Before we implement these methods in StudentDTO, ensure that AddressDTO has equals and hashCode properly overridden. I’ll not provide an explicit implementation for AddressDTO as it depends on its fields, but it would follow a similar pattern to StudentDTO.

Step 2: Implement equals and hashCode in StudentDTO

import java.util.Objects;

@Data
public class StudentDTO {
    public AddressDTO address;
    public String name;

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

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

Remember, the equals and hashCode methods of AddressDTO must be correctly overridden for this to work as expected, considering the fields of AddressDTO that determine equality.