Sobes.tech
Junior — Middle

How can you check for equality of values in object fields?

sobes.tech AI

Answer from AI

In Java, to check the equality of object field values, the equals() method is usually overridden. By default, the equals() method compares object references (i.e., checks if they point to the same object in memory), but for content comparison, custom logic needs to be implemented.

Example of overriding equals() for a class with two fields:

public class Person {
    private String name;
    private int age;

    @Override
    public boolean equals(Object obj) {
        if (this == obj) return true; // reference equality check
        if (obj == null || getClass() != obj.getClass()) return false; // null and class check
        Person other = (Person) obj;
        return age == other.age && (name != null ? name.equals(other.name) : other.name == null);
    }

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

It is also important to override hashCode() so that objects equal according to equals() have the same hash code, which is crucial for correct operation in collections like HashSet or HashMap.

If you just want to compare field values without overriding, you can compare them directly, for example:

if (obj1.getName().equals(obj2.getName()) && obj1.getAge() == obj2.getAge()) {
    // objects are equal based on fields
}
How can you check for equality of values in object… - sobes.tech