Java Overrides equals(), hashCode(), compareTo()

- 2 mins

Two rule when dealing with object identification in Java

  1. Override hashCode when you override equals
  2. Make conpareTo consistent with euqals

Default equals is based on memory location of two objects, so we need to customize it to meet our need.

  1. equals must conform to rules:
    • x.equals(x)
    • x.equals(y) then must y.equals(x)
    • x.equals(y) and y.equals(z) then x.equals(z)
    • mutiple invocations of x.equals(y) return same
    • if x is not null, x.equals(null) return false
  2. Five-step for overridding equals()
     public class SampleEquals {
         private int val1;
         private int val2;
         ...
    
         public boolean equals (Object o) {
             //step 1: check if o is current object (== checks addresses in memory)
             if(this == o){
                 return true;
             }
    
             // step 2: instance check
             if (!(o instanceof SampleEquals)) {
                 return false;
             }
    
             // step 3: cast
             SampleEquals other = (SampleEquals) o;
    
             // step 4: customized check
             return other.val1 == this.val1 && other.val2 == this.val2;
    
             // step 5: checks all the rules for equals() above
         }
     }
    

hashCode() method of objects is used when you insert them into a HashTable, HashMap or HashSet.

compareTo() is used to implement natural sorting on Java classes

rss facebook twitter github gitlab youtube mail spotify lastfm instagram linkedin google google-plus pinterest medium vimeo stackoverflow reddit quora quora