https://stackoverflow.com/questions/18565701/stringbuilder-equals-java
https://stackoverflow.com/questions/11112602/why-does-stringbuffer-stringbuilder-not-override-equals-or-hashcode
Yes,
StringBuilder does not override Object's .equals() function
, which means the two object references are not the same and the result is false.
For
StringBuilder
, you could use s1.toString().equals(s2.toString())
https://stackoverflow.com/questions/11112602/why-does-stringbuffer-stringbuilder-not-override-equals-or-hashcode
Because
StringBuffer
is mutable, and its primary use is for constructing strings. If you want to compare content, call StringBuffer#toString()
and compare the returned value.
It is not generally useful to override
hashCode()
for mutable objects, since modifying such an object that is used as a key in a HashMap
could cause the stored value to be "lost."
Actually behind this everything depends upon hashcode code value. To understand this concept lets take an example :
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. It should be added in HashMap ? Answer is NO. Because before inserting/putting value in HashMap, it internally checks and compare hashCode value of str1, str2. Both retun same hascode value because String class override equals() and hashcode() method. So upon executing
hm.put(str2,"bye");
first key will get override with 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}
Sun Microsystem wanted the programmer to allow adding 2 different String kind of Values in Hashtable ...
That's not true, javadocs for Hashtable
and Map
actively discourage using objects with a broken equals/hashcode
contract as keys. Storing StringBuilder
objects in a map isn't useful because you won't be able to get the value by the key unless you have your original object