0

i'm trying to compare to objects using the equals method but it always returns false

public class main {
    public static boolean match(house h1,house h2) {
        if(h2.equals(h1)) {
            return true;
        }
        else {
            return false;
        }
    }
    public static void main(String[] args) {
        house myHouse1 = new house("jj",5,5);
        house myHouse2 = new house("jj",5,5);
        
        System.out.println(match(myHouse1,myHouse2));

    }

}
aj ada
  • 21
  • 9
    How is equals implemented in house? – Rick Nov 18 '21 at 11:13
  • 2
    Does class `house` override method [equals](https://stackoverflow.com/questions/8180430/how-to-override-equals-method-in-java) ? – Abra Nov 18 '21 at 11:14
  • 3
    If you did not override `equals` and `hashCode` in `house`, then yes, `h1` and `h2` are two distinct instances. – sp00m Nov 18 '21 at 11:14
  • 1
    Unless you explicitly override the `equals(Object o)` method in your custom type it will just compare the instance hash instead of the contents of the object. – Igor Flakiewicz Nov 18 '21 at 11:14
  • You should override equals method in house class – Marwen Jaffel Nov 18 '21 at 11:14
  • You can automatically override `equals` and `hashCode` method in your `house` class with IntelliJ. Right click on class -> Generate -> equals and hashCode – Fenio Nov 18 '21 at 11:20

1 Answers1

3

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 House1, 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 record2 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).

MC Emperor
  • 22,334
  • 15
  • 80
  • 130