jQuery in Action, 2nd edition*
The moose likes Beginning Java and the fly likes Why Stringbuffer not implemented equals method Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Reply locked New topic
Author

Why Stringbuffer not implemented equals method

imaya Munusamy
Greenhorn

Joined: May 19, 2008
Posts: 20
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

Joined: Jan 30, 2000
Posts: 18671
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.


"I'm not back." - Bill Harding, Twister
imaya Munusamy
Greenhorn

Joined: May 19, 2008
Posts: 20
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

Joined: Oct 13, 2005
Posts: 37902
    
  22
"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 ]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Why Stringbuffer not implemented equals method
 
Similar Threads
StringBuffer equals() method
StringBuffer doubt
StringBuffer and String doubt
Equal method
Difference of equals method in string and stringbuffer