Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

StringBuffer equals() method

 
md ali
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,
StringBuffer sb1 = new StringBuffer("hello");
StringBuffer sb2= new StringBuffer("hello");
System.out.println(sb1.equals(sb2));
Why this code prints false. Is there some difference in StringBuffer equals() method.
Regards
Muhammad Ali
 
Abdul Latif
Ranch Hand
Posts: 89
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There is no equals method defined for the StringBuffer class
& so it uses the equals method inherited from the Object class
& the Object class equals method does not work properly as intended. For your code to return true u have to subclass SringBuffer & provide equals method for it.
hope this helps
 
md ali
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It is strange thing. Are there also some other classes from Sun which do not have a well defined equals method. And can somebody tell that what is the reason for not having an equals() method well defined in StringBuffer or any other class.
Regards
Muhammad Ali
 
Jane Griscti
Ranch Hand
Posts: 3141
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi md,
The default 'equals()' returns 'true' if both references point to the same object in memory. That's an easy 'value' to determine.
'equality' has to do with comparing values; one person's idea of 'equality' may be different from anothers.
Overriding equals() for String and the wrapper classes (Boolean, Double, Integer, etc) was an easy call for the developers as the classes are immutable and it's not difficult to arrive at a consensus as to what qualifies as a useful 'value'.
For mutable objects it might be tougher. Are StringBuffers equal only if they are the same size and have the same characters? or only if they have the same characters, regardless of the buffer size? or only if they have the same set of contiguous characters? or only if ... you see the problem
Hope that helps.
------------------
Jane Griscti
Sun Certified Programmer for the Java� 2 Platform
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic