When overriding the equals() and hashCode() methods of a class, would the following approach work?
All my logic to see if the objects are equal is done in my equals() method. The class has a static variable (we’ll call it hashCodeReturn) that is set to 1.
When ever the equals method reaches logic that would return false, it adds 1 to hashCodeReturn
The hashCode() then simply returns the hashCodeReturn value
Is there any reason this would not work?
Many thanks.
No, it would not work.
The hash code of two objects that are the same (e.g. the same reference) should be the same. By returning the result of a static variable you’ll break this contract.