-2

Consider the following three statements in Java:

  1. StringBuilder s1 = new StringBuilder("Boo");
  2. StringBuilder s2 = new StringBuilder("Boo");
  3. String s3 = new String ("Boo");

Why does s1.equals(s2) return false?

Derrick
  • 3,669
  • 5
  • 35
  • 50
  • 5
    From the [documentation](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/StringBuilder.html): "StringBuilder implements Comparable but does not override equals. Thus, the natural ordering of StringBuilder is inconsistent with equals." – Federico klez Culloca Nov 09 '18 at 11:28
  • use toString() for equality check – Derrick Nov 09 '18 at 11:29

1 Answers1

4

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.

Sid
  • 4,893
  • 14
  • 55
  • 110