Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing string equality using hashCode()

Is there any reason why a Java string cannot be tested for equality using its hashCode method? So basically, instead of....

"hello". Equals("hello")

You could use...

"hello".hashCode() == "hello".hashCode()

This would be useful because once a string has calculated it's hashcode then comparing a string would be as efficient as comparing an int as the string caches the hashcode and it is quite likely that the string is in the string pool anyway, if you designed it that way.


1 Answers

Let me give you a counter example. Try this,

public static void main(String[] args) {
    String str1 = "0-42L";
    String str2 = "0-43-";

    System.out.println("String equality: " + str1.equals(str2));
    System.out.println("HashCode eqauality: " + (str1.hashCode() == str2.hashCode()));
}

The result on my Java,

String equality: false
HashCode eqauality: true
like image 75
ZZ Coder Avatar answered Sep 15 '25 03:09

ZZ Coder