Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing StringBuffer content with equals

Tags:

java

StringBuffer sb1 = new StringBuffer("Java"); StringBuffer sb2 = new StringBuffer("Java"); System.out.println(sb1 == sb2); System.out.println(sb1.equals(sb2)); 

Here both are returning false. How is it possible?

like image 295
GuruKulki Avatar asked Jan 06 '10 10:01

GuruKulki


1 Answers

The equals method of StringBuffer is not overridden from Object, so it is just reference equality, i.e., the same as using ==. I suspect the reason for this is that StringBuffer is modifiable, and overriding equals is mostly useful for value-like classes that you might want to use as keys (though lists also have an overridden equals and StringBuffer is kind of a list, so this is a bit inconsistent).

like image 152
JaakkoK Avatar answered Sep 20 '22 02:09

JaakkoK