Won't it be worthwhile to also ensure that - if theirDefinitely not. Heres the thing: A strings hashcode is calculated using some mathematical formula that depends on all of the letters. Doing a string comparison, if the first 2 characters don't match, you can return false right there. So calculating hashcodes first could definitely make performance a lot worse and wouldn't make it a lot better.
hash is available, the hash matches before comparing
the entire string character arrays? Seems like that
would offer a significant performance boost.
On the other hand, since String is immutable, it isYes hashcode is is calculated just once and stored in the hash member. Refer hashCode() implementation.
possible that its hashCode() method just calculates
the hash code once, the first time it is requested,
and then caches the result.
Yes hashcode is is calculated just once and stored inThat's c%l, but notice that the API doesn't mention caching,
the hash member. Refer hashCode() implementation.
I remember reading somewhere that originally theHowever, remember the hashCode contract: equal objects must have equal hash codes. Refer: http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Object.html#hashCode()
hashCode wasn't computed based on all the characters
in the string -- it only sampled a few for efficiency
sake. Here's the API for version 1.0.2 -- there's no
mention of what algorithm is used. Hmmm:
So implementations, high-level algorithms, every API
specs change over time. YMMV.
Therefore, it is reasonable to infer that the hashcodes, if present and not equal means that theI agree that different hash codes imply nonequal objects. The "content is checked only when" part is your addition. Feel free say this is a reasonable thing to infer, but reasonable is not a legal contract.
two strings are not equal. Content is checked only when:
a) Length is equal and
b) Hash codes are absent/equal
You're probably saying the same thing. I'm justYes, we are trying to same the same thing here. If hash codes are equal, then no doubt content must be checked and verified to ensure that two strings are indeed same - which covers the above usecase.
trying to add weight to the whole different hash
codes == unequal objects thing... :o)