| Author |
Why StringBuffer does not override equals & hashCode
|
Costa lamona
Ranch Hand
Joined: Sep 24, 2006
Posts: 102
|
|
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 ?
|
SCJP 5
|
 |
Ernest Friedman-Hill
author and iconoclast
Marshal
Joined: Jul 08, 2003
Posts: 23395
|
|
|
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.
|
[Jess in Action][AskingGoodQuestions]
|
 |
Jim Yingst
Wanderer
Sheriff
Joined: Jan 30, 2000
Posts: 18652
|
|
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.
|
"I'm not back." - Bill Harding, Twister
|
 |
Costa lamona
Ranch Hand
Joined: Sep 24, 2006
Posts: 102
|
|
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
Joined: Sep 24, 2006
Posts: 102
|
|
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 !!
|
 |
 |
|
|
subject: Why StringBuffer does not override equals & hashCode
|
|
|