Override equals and hashCode in Java
Equals and hashCode in Java are two fundamental method which is declared in Object class and part or core Java library. equals() method is used to compare Objects for equality while hashCode is used to generate an integer code corresponding to that object. equals and hashCode has used extensively in Java core library like they are used while inserting and retrieving Object in HashMap, see how HashMap works in Java for full story, equals method is also used to avoid duplicates on HashSet and other Set implementation and every other place where you need to compare Objects. Default implementation of equals() class provided by java.lang.Object  compares memory location and only return true if two reference variable  are pointing to same memory location i.e. essentially they are same  object. Java recommends to override equals and hashCode  method if equality is going to be define by logical way or via some  business logic and many classes in Java standard library does override  it e.g. String overrides equals,  whose implementation of equals() method return true if content of two String objects are exactly same. Integer wrapper class overrides equals to perform numerical comparison etc.
 
0 comments:
Post a Comment