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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • paul wheaton
  • Liutauras Vilda
  • Ron McLeod
Sheriffs:
  • Jeanne Boyarsky
  • Devaka Cooray
  • Paul Clapham
Saloon Keepers:
  • Scott Selikoff
  • Tim Holloway
  • Piet Souris
  • Mikalai Zaikin
  • Frits Walraven
Bartenders:
  • Stephan van Hulst
  • Carey Brown

Why Stringbuffer not implemented equals method

 
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Report post to moderator
I couldn't imagin any reason why Stringbuffer has not implemented equals method....it will break if we use String buffer in HashMap or HashSet.. can some one explain it
 
Wanderer
Posts: 18671
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Report post to moderator
Well, a Map or Set assumes that the keys (for Map) or values (for Set) will not change. And the entire purpose of a StringBuffer is to change its content. Which makes them extremely poor choices to use in a Map or Set - if you change the content of a StringBuffer after you use it as a key in a Map, the map won't work correctly. There are two basic options:

1. If you're dong changing the content of the StringBuffer, use toString() to convert it to an immutable String, and use the String as the key in your Map.

2. If you're not done changing the content of the StringBuffer, don't even try to use it as a key in a Map. It will only cause you pain.
 
imaya Munusamy
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Report post to moderator
hi Jim ,

do you mean we should use only immutable object in Hashmap or Hashset? lot of time we 'll use our custom class (Eg: Student.class) objects as key in hashmap which is mutable which can be modified even after put in collection. developer has to take care of this.



this shouldn't be the reason for not implementing equals in Stringbuffer
 
Marshal
Posts: 80138
418
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Report post to moderator
"Imaya M," as Joanne Neal has already hinted about, on this thread, you ought not to be asking the same question twice.

To avoid the discussion become even more fragmented, I shall close this thread.
[ May 29, 2008: Message edited by: Campbell Ritchie ]
 
Crusading Chameleon likes the size of this ad:
Smokeless wood heat with a rocket mass heater
https://woodheat.net
    Bookmark Topic Watch Topic
  • New Topic