Equals Method in StringBuffer
Consider this code snippet
StringBuffer s1 = new StringBuffer("shankh");
StringBuffer s2 = new StringBuffer("shankh");
System.out.println("Equality Check 1:"+(s1==s2)); //returns false as expected
System.out.println("Equality Check 2:"+(s1.equals(s2)));
//returns false but was expecting true
Why did the equals method return false? The answer lies in one of the most common mistakes of Java equals usage. StringBuffer doesn’t override the equals method and it is using the equals method inherited from Object. So behind the scenes you ended up checking this if(s1==s2) and not comparing the contents.
http://java.sun.com/j2se/1.5.0/docs/api/java/lang/StringBuffer.html
http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Object.html#equals%28java.lang.Object%29states
“The equals method for class Object implements the most discriminating possible equivalence relation on objects; that is, for any non-null reference values x and y, this method returns true if and only if x and y refer to the same object (x == y has the value true).”
If you want to compare the contents of StringBuffer then this is one way of doing it.
System.out.println("Equality Check 3:"+(s1.toString().equals(s2.toString())));
//true as expected
It works fine as String overrides the equal method defined in Object Class.
There is an interesting article written by the Scala guys(Martin Odersky, Lex Spoon, and Bill Venners) about implementing equality in Java. http://www.artima.com/lejava/articles/equality.html

![Reblog this post [with Zemanta]](http://img.zemanta.com/reblog_e.png?x-id=29478ef7-cb2a-4363-9d4f-3dd2be27c5d0)
Leave a Reply