Thursday, January 2, 2020

Why does StringBuffer/StringBuilder not override equals or hashCode?

String str1 = new String("sunil");
String str2 = new String("sunil");

HashMap hm = new HashMap()
hm.put(str1,"hello");
hm.put(str2,"bye");
final hm:

hm = { sunil=bye }
In above code, str1 and str2 are two different String objects. Should they be added to the HashMap separately? The answer is NO. This is because before inserting/putting a value in HashMap, it internally checks and compares the hashCode values of str1, str2. Both return the same hashcode value because the String class overrides equals() and hashcode() methods. So upon executing hm.put(str2,"bye"); first key will get overriden with the new value. Now try this :

StringBuilder sb1 = new StringBuilder("sunil");
StringBuilder sb2 = new StringBuilder("sunil");

HashMap hm = new HashMap()
hm.put(sb1,"hello");//sb1 and sb2 will return different HashCode
hm.put(sb2,"bye");// StringBuffer/StringBuilder does not override hashCode/equals methods
final hm:

{sunil=hello, sunil=bye}
Both value will be added in hashMap because sb1 and sb2 both returns different hashcode. StringBuilder/ StringBuffer does not override equals() and hashCode() method.

Sun Microsystem wanted the programmer to allow adding 2 different String kind of Values in Hashtable or any other Hash Collections likes (HashSet,HashMap…),that’s the reason hashCode() and equals() were not overridden intentionally in StringBuffer,StringBuilder class.

No comments:

Post a Comment