Both code examples work. if (this == o) return true; in the first example - performance optimization (most likely, premature optimization is always a profile profile) which checks whether the object is compared with itself. In Java, the == operator compares whether two objects are the same instance, and not whether they are different instances with the same data.
There are writing styles for the equals method. This is how I usually do it:
public boolean equals(Object obj) { if (obj instanceof Product) { Product that = (Product) obj; return this.id == that.id; } return false; }
If I know that my code will never compare an object with objects of other types or against null, then I can even write the code as shown below to throw an exception if this happens one way or another - this will mean that my code there is a mistake, therefore, not having managed early, I will find out about it and fix it sooner.
public boolean equals(Object obj) { Product that = (Product) obj; return this.id == that.id; }
source share