Differences between Hashcode and Equals in Java


Hashcode Equals

Both are methods of java.lang.Object class. Hashcode is an integer representation of the objects of an array, String and a DS. Hashcode increases the performance of comparing these three. For example. to compare two long strings with many number of characters, writing a for loop and comparing each character takes a very good time. Java adopts hashcode technique to compare. That is, both strings are converted into integer values (known as hashcode) by Java and then these two integer values are compared. If both integers (compared with ==) are equal, then the two strings contain the same characters in the same order.

Both these methods are illustrated in Object comparison – hashCode() & equals().

2 thoughts on “Differences between Hashcode and Equals in Java”

  1. public class equahas {

    public static void main(String[] args) {
    // TODO Auto-generated method stub
    String st = new String (“mukesh”);

    String st2=new String(st);

    String st3= new String (“mukesh”);

    int i=st.hashCode();

    int j=st2.hashCode();

    int k=st3.hashCode();

    System.out.println( “oprator st==st2::” + (st == st2));
    System.out.println( “st equals st2::”+st.equals(st2));

    System.out.println(“oprator st==st3 ::” +(st==st3));
    System.out.println(“st equals st3::” +st.equals(st3));

    System.out.println(“i=”+i+”j=”+j+”k=”+k);
    }

    }

    output of this code
    oprator st==st2::false
    st equals st2::true
    oprator st==st3 ::false
    st equals st3::true
    i=-1063049513j=-1063049513k=-1063049513

    St and st2 are equals , but both are not same objects. again st and st3 are equals but st==st3 is false means not same objects all st ,st2,st3 having same hash code and st, st2,st3 are equals .

Leave a Comment

Your email address will not be published.