Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
    Bookmark Topic Watch Topic
  • New Topic

Why Stringbuffer not implemented equals method

 
imaya Munusamy
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • 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
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • 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
  • 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
 
Campbell Ritchie
Sheriff
Pie
Posts: 49776
69
  • Mark post as helpful
  • send pies
  • 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 ]
 
    Bookmark Topic Watch Topic
  • New Topic