Consider the following three statements in Java:
StringBuilder s1 = new StringBuilder("Boo");
StringBuilder s2 = new StringBuilder("Boo");
String s3 = new String ("Boo");
Why does s1.equals(s2)
return false
?
Consider the following three statements in Java:
StringBuilder s1 = new StringBuilder("Boo");
StringBuilder s2 = new StringBuilder("Boo");
String s3 = new String ("Boo");
Why does s1.equals(s2)
return false
?
The StringBuilder class in Java is unlike others wherein it does not override equals
and hashcode
. If you are new to Java, it may not be immediately apparent that if a class does not provide an overriden implementation of equals
, the system uses the Object
class' equals
method, which is no different than comparing the references, aka the memory pointer.
StringBuilder s1 = new StringBuilder("Boo");
StringBuilder s2 = new StringBuilder("Boo");
s1.equals(s2) // false
s1.toString().equals(s2.toString()) // true because String overrides equals
s1 = s2
s1.equals(s2) // true because same reference
It would be wise to convert the StringBuilder objects to String by using the toString
method and then comparing it.
EDIT: Did some googling to understand why StrintBuilder
& StringBuffer
does not override equals
& hashcode
. It turns out that the reason is that objects of these classes are expected to be mutated heavily, and hence it may not be good design to use them for hashing/comparison. Strings on the other hand are immutable. Seems these are just meant to be containers for Strings with added functionality.