Java_Core_Senior_PreJava8_Interview_Problems
Java_Core_Senior_PreJava8_Interview_Problems
Concurrency, JMM)
How would you override equals() and hashCode() properly in a custom class?
The equals() method must check logical equivalence, not reference equality.
Steps to override equals():
Check if 'this == obj'.
Check if obj is not null and is of the same class.
Cast and compare relevant fields.
The hashCode() method must return equal hash codes for equal objects.
Guidelines:
Use a consistent and well-distributed hash function.
Include the same fields used in equals().
Example:
Use prime numbers in hash computation: int result = 31 * result + field.hashCode();
Violating the equals-hashCode contract breaks behavior in hash-based collections.