Summary & Miscellaneous Tips about hashCode and equals method
- Equal objects must produce the same hash code as long as they are equal, however unequal objects need not produce distinct hash codes.
- The
equalsmethod provides "deep comparison" by checking if two objects are logically equal as opposed to the "shallow comparison" provided by the equality operator==. - However, the
equalsmethod injava.lang.Objectclass only provides "shallow comparison", same as provided by the equality operator==. - The
equalsmethod only takes Java objects as an argument, and not primitives; passing primitives will result in a compile time error. - Passing objects of different types to the
equalsmethod will never result in a compile time error or runtime error. - For standard Java wrapper classes and for
java.lang.String, if theequalsargument type (class) is different from the type of the object on which theequalsmethod is invoked, it will return false. - The class
java.lang.StringBufferdoes not override theequalsmethod, and hence it inherits the implementation fromjava.lang.Objectclass. - The
equalsmethod must not provide equality comparison with any built in Java class, as it would result in the violation of the symmetry requirement stated in the general contract of theequalsmethod. - If
nullis passed as an argument to theequalsmethod, it will return false. - Equal hash codes do not imply that the objects are equal.
return 1;is a legal implementation of thehashCodemethod, however it is a very bad implementation. It is legal because it ensures that equal objects will have equal hash codes, it also ensures that the hash code returned will be consistent for multiple invocations during the same execution. Thus, it does not violate the general contract of thehashCodemethod. It is a bad implementation because it returns same hash code for all the objects. This explanation applies to all implementations of thehashCodemethod which return same constant integer value for all the objects.- In standard JDK 1.4, the wrapper classes
java.lang.Short, java.lang.Byte, java.lang.Characterandjava.lang.Integersimply return the value they represent as the hash code by typecasting it to anint. - Since JDK version 1.3, the class
java.lang.Stringcaches its hash code, i.e. it calculates the hash code only once and stores it in an instance variable and returns this value whenever thehashCodemethod is called. It is legal becausejava.lang.Stringrepresents an immutable string. - It is incorrect to involve a random number directly while computing the hash code of the class object, as it would not consistently return the same hash code for multiple invocations during the same execution.

