In java, when I use a String as a key for Hashmap I get a little different result than when I use the string hashcode as a key in the HashMap.
Any insight?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You mustn’t use the hash code itself as the key. Hash codes aren’t intended to be unique – it’s entirely permitted for two non-equal values to have the same hash code. You should use the string itself as a key. The map will then compare hash codes first (to narrow down the candidate matches quickly) and then compare with
equalsfor genuine string equality.Of course, that’s assuming your code really is as your question makes it, e.g.
If that’s really what your code looks like, just use
HashMap<String, String>instead.From the docs for
Object.hashCode()(emphasis mine):