Why always do this: A other = (A) obj; other.a A other = (A) obj; other.a , instead of referring to a variable of the passed object obj.a ?

  public boolean equals(Object obj) { if (obj==null) return false; if (obj.getClass() != this.getClass() ) return false; A other = (A) obj; return this.a* other.b== this.b* other.a; } 
  • 3
    Who always does this and where and since when does it compile at all? - Qwertiy
  • probably you didn’t like the Object class, now changed it to class A. But I don’t understand why it wouldn’t compile? - Nikita Ryazan
  • @Qwertiy Well, if the fields a and b type Integer , for example, then it will be fully compiled. Although the logic of comparison is still strange. - andreycha
  • one
    @andreycha need not be so categorical. I will give an example, there is a parent class, there are classes descendants. Your method will work only with the parent class, which is not always good. - Artem Konovalov
  • one
    @ArtemKonovalov well, then it is probably worth clarifying that "it is better in some cases." Because in general this is a very controversial idea. On the one hand, using getClass() leads to violation of the LSP, on the other hand, using instanceof() leads to violation of the equality x.equals(y) == y.equals(x) . - andreycha

1 answer 1

This standard implementation. The interface implies that any object can get into the equals() method.

Accordingly, we first need to find out whether the test makes sense: if this object is null or of a different type, then we are definitely not equal to it ( return false; ).

After we figured out that the transferred object is of the type we need, we can compare the fields. But we are given a parameter of type Object , and in it the fields a and b missing. Therefore, we reduce it to our type A ( A other = (A) obj; ), and a new object is not created. And now we can refer to the fields a and b .

PS True, the comparison logic is strange. The idea should be like this:

 return this.a == other.a && this.b == other.b; 
  • 2
    I think that the vehicle is actually a rational fraction. - VladD
  • 2
    @VladD then there will be problems with getHashCode() . - andreycha
  • @VladD Yes, and with multiplication there can be problems if the numbers are close to the maximum values. - Alexandr
  • Yeah, but for the time being, the TS does not understand why Object cannot have access to the fields a and b (that is, it does not understand the difference between the declared and actual types), but you mean high matters. - VladD
  • @VladD Well, about high matters, we are talking to each other :). - andreycha