Shankh is London based consultancy started on 2011 to provide consultancy services primarily in Java. With several successful Java projects under our belt, we started exploring mobile based services towards end of 2012 which led to our first android/ios/windows-phone app which is staged for release in 2013

Some Random quotes

Innovation distinguishes between a leader and a follower. -Steve Jobs

It is not that i am smarter than others, i just persist with problems longer

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.
“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.

Reblog this post [with Zemanta]

Leave a Reply