• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Why StringBuffer does not override equals & hashCode

 
Costa lamona
Ranch Hand
Posts: 102
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi

I have this guess, that it is because sun wants to discourage usage of StringBuffer as an entry to HashThings, because hashing function of big strings will cost alot of processor cycles; It will contain alot of multiplications and exponentials.

Is that correct ?
, and Is there another reasons ?
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24212
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
My guess is because StringBuffer is one of the very oldest classes, and they made lots of little mistakes like this back then. It's true that StringBuffers wouldn't good hash keys, not for the reasons you gave, but simply because their hashCode() would necessarily change when the contents change, and objects whose hashCodes change a lot make lousy keys. But I don't think that much thought went into this design; I think somebody just forgot.
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes - had they thought about it more, it would've been more appropriate to just throw an UnsupportedOperationException the moment anyone called either hashCode() or equals() on a StringBuffer.
 
Costa lamona
Ranch Hand
Posts: 102
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Ernest Friedman-Hill:
... and objects whose hashCodes change a lot make lousy keys. But I don't think that much thought went into this design; I think somebody just forgot.


Yes, But I would say that hashCodes that depend on data which is "changeble" through the class API , will make corrupted hashThings, ie you will not find your stuff, if you change the object content after it has added to the HashThing.

how I did not think about it, the String could be huge too, and StringBuilder is mutable

Thanks
 
Costa lamona
Ranch Hand
Posts: 102
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Jim Yingst:
Yes - had they thought about it more, it would've been more appropriate to just throw an UnsupportedOperationException the moment anyone called either hashCode() or equals() on a StringBuffer.


and that is better than having very nasty bugs, due to you, programmer will think that he is using appropriate equals and hashCode, while he is using the Object version.

or may be they should use mark interface sounds like
Hashable, just like clone method !!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic