You have to implement the equals
method yourself.
The equals
method does not magically test whether two instances of your custom class are considered "equal" to eachother. You must define when two of your objects are equal yourself.
Since you did not implement equals
yourself, then the implementation of Object
is selected (in your case), which only compares by identity. Two objects created by new
always have distinct identities, that is, two separate chunks in memory, despite having exactly the same fields.
So you need to override equals
(and, by contract, also hashCode
). Note that the equals
method must accept an Object
rather than a House
1, that is, public boolean equals(Object other) { ... }
.
What are the options to implement equals
?
You have a few options to implement equals
(and hashCode
):
- Write it yourself by hand. More information: How to override equals method in Java
- Use your IDE to generate them for you. Fenio already provided how to do this in IntelliJ in the comments. In Netbeans, open the class, right-click on the source code and click on Insert Code... → equals() and hashCode()... and then select the fields to include in the comparison.
- Use Lombok to generate them for you, using the
@EqualsAndHashCode
annotation.
- Turn your
House
into a record
2 and you get equals
and hashCode
for free.
1 Class names should be written in PascalCase according to the Java Naming Conventions, so house
should be House
.
2 Records are available since Java 16 (and in Java 14 and 15 as preview features).