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
equals
method provides "deep comparison" by checking if two objects are logically equal as opposed to the "shallow comparison" provided by the equality operator==
. - However, the
equals
method injava.lang.Object
class only provides "shallow comparison", same as provided by the equality operator==
. - The
equals
method 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
equals
method will never result in a compile time error or runtime error. - For standard Java wrapper classes and for
java.lang.String
, if theequals
argument type (class) is different from the type of the object on which theequals
method is invoked, it will return false. - The class
java.lang.StringBuffer
does not override theequals
method, and hence it inherits the implementation fromjava.lang.Object
class. - The
equals
method 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 theequals
method. - If
null
is passed as an argument to theequals
method, it will return false. - Equal hash codes do not imply that the objects are equal.
return 1;
is a legal implementation of thehashCode
method, 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 thehashCode
method. It is a bad implementation because it returns same hash code for all the objects. This explanation applies to all implementations of thehashCode
method 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.Character
andjava.lang.Integer
simply return the value they represent as the hash code by typecasting it to anint
. - Since JDK version 1.3, the class
java.lang.String
caches its hash code, i.e. it calculates the hash code only once and stores it in an instance variable and returns this value whenever thehashCode
method is called. It is legal becausejava.lang.String
represents 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.