Win a copy of Five Lines of Code this week in the OO, Patterns, UML and Refactoring forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Bear Bibeault
  • Ron McLeod
  • Jeanne Boyarsky
  • Paul Clapham
Sheriffs:
  • Tim Cooke
  • Liutauras Vilda
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • fred rosenberger
  • salvin francis
Bartenders:
  • Piet Souris
  • Frits Walraven
  • Carey Brown

StringBuffer equals() method

 
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
 
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
 
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
 
Consider Paul's rocket mass heater.
    Bookmark Topic Watch Topic
  • New Topic