This question has already been answered:

Good day.

There is an example implementation of the equals () method:

public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Vertex vertex = (Vertex) o; return Objects.equals(getId(), vertex.getId()) && getState() == vertex.getState() && Objects.equals(getVertices(), vertex.getVertices()); } 

The question arises, what is the specific essence of this test?

 getClass() != o.getClass() 

Thank you.

Reported as a duplicate by Grundy , Qwertiy participants , user194374, Alex , aleksandr barakin 7 Dec '16 at 12:56 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

  • Ohh ... It means exactly what is written. Is the class of the current object equal to the class of the argument? This, it seems, is directly written, it is only necessary to read. What is the essence of the question? - D-side
  • But for what purpose to compare the classes if the first condition, if (this == o) , has not been fulfilled? - Dmitry08
  • Because it checks the identity of objects (which is actually one object), but not their equality. We, it seems, had a canonical question here on different types of equality ... - D-side
  • For reference types, the == operator does not compare the objects themselves, but where they refer to. Two objects can be identical, but their references will refer to different values. If two links refer to the same object, then there is no need to check anything further on the equivalence of objects - SlandShow
  • Yes, I completely agree with this. Thank you. - Dmitry08

1 answer 1

In the Object class, the equals method takes as an argument an object of type Object . Because of this, you have to use validation when overriding a method. The expression getClass() != o.getClass() does just that, so that the subsequent cast is correct: Vertex vertex = (Vertex) o;

  • It seems to have dealt with this issue. Thank you. - Dmitry08
  • Not this way. Bringing it would be correct for the heirs. And here the coincidence of the type is ideologically checked. - Qwertiy
  • I agree, a somewhat strange implementation of equals , usually there is an instanceof check - Artem Konovalov