Override equals method

new question here:

So, in my homework at the university, I have to redefine the object class method for the new class I created.

The new class is the “Product”, each product has an attribute “id”, which is unique. So this is how I redefined it:

@Override
public boolean equals(Object obj) {
       final Product other = (Product) obj;
       if (id != other.id)
           return false;
       return true;
   }

The fact is that this is 1.5 out of 10 points, and this made me suspiciously so simple. So I started the search, and I found things like:

@Override
public boolean equals(Object obj) {
       if (this == obj)
           return true;
       if (obj == null)
           return false;
       if (getClass() != obj.getClass())
           return false;
       final Product other = (Product) obj;
       if (id != other.id)
           return false;
       return true;
   }

Which makes no sense to me, because I think the latter, if you check all the other ifs restrictions. What do you guys think? What is the best way to override this method?

Thank!

+3
source share
5 answers

The second part of the code is better:

  • x.equals(x), , .
  • x.equals(null) , NullPointerException
  • , ClassCastException, (, x.equals("foo"))
  • ; obj.equals(x) , .
+14

, , . ClassCastException, , obj . , this.getClass() != obj.getClass() ( instanceof).

Product p = new Product();
p.equals("abc");

, false.

, product.equals(null), false, equals . , , :

...
Product p = (Product)obj; // obj is null
obj.id // this throws a NullPointerException
+2

, equals(),

@Override
public boolean equals(Object obj) {
       if (! (obj instanceof Product) ) return false;

       final Product other = (Product) obj;
       if (id != other.id)
           return false;
       return true;
   }

, :

  • , () , . , , .
  • , Product, equals(). (, , , .) - , ().
+1

2 Java . 1 nullpointer, Object null, , ( , ojb )

0

, : Java (, Product , Object):

@Override
public boolean equals(Object obj) {
    if (this == obj) return true;
    if (!(obj instanceof Product)) return false;
    final Product other = (Product) obj;
    if (id != other.id) return false;
    return true;
}

:

  • new Product(1).equals(null) NullpointerException, , false Object.equals().
  • new Product(1).equals(new Vector()) ClassCastException, , false Object.equals().

. if (this == obj) return true; , , , .

The second solution that appears makes it difficult to subclass Product with good semantics. If you have a subclass

public class SubProduct extends Product {
    SubProduct(int id) {
         super(id);
    }
    ...
}

you will have !new Product(4).equals(new SubProduct(4)). This violates the principle of the Lisb suspect and is often considered not very good. If you have the last class, the second solution is the same as above.

0
source

All Articles