How would you ensure that equals() properly compares two user profile objects based on their unique identifiers?

To compare user profile objects based on a unique identifier, the equals() method should be overridden so that two objects are considered equal when their unique IDs match. Since collections such as HashMap and HashSet rely on both equals() and hashCode(), it is essential to override hashCode() as well to maintain consistency and ensure correct behavior.

Key Points: • equals() should compare only the unique identifier if it uniquely represents the object. • hashCode() must be overridden whenever equals() is overridden to satisfy the Java contract. • Proper implementation prevents duplicate entries and ensures reliable behavior in hash-based collections.

Example: In a user management system, two UserProfile objects may have different names or email addresses but represent the same user if they share the same userId. In such cases, equality should be based on userId rather than all attributes.

Code Example:

import java.util.Objects;

class UserProfile {

    private Long userId;
    private String name;

    public UserProfile(

Long userId,

            String name) {

        this.userId = userId;
        this.name = name;
    }

    @Override
    public boolean equals(
            Object obj) {

        if (this == obj) {
            return true;
        }

if (obj == null ||

            getClass() != obj.getClass()) {
            return false;
        }

        UserProfile other =
                (UserProfile) obj;

return Objects.equals(

                this.userId,
                other.userId);
    }

    @Override
    public int hashCode() {

        return Objects.hash(userId);
    }
}

Interview Tip: A concise interview answer is: To compare user profile objects by their unique identifier, I override equals() to compare only the unique ID and override hashCode() using the same field. This ensures consistent equality checks and correct behavior in collections such as HashSet and HashMap.