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?
when I use the string hashcode as a key in the HashMap.
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 equals
for genuine string equality.
Of course, that's assuming your code really is as your question makes it, e.g.
HashMap<String, String> goodMap = new HashMap<String, String>();
goodMap.put("foo", "bar");
HashMap<Integer, String> badMap = new HashMap<Integer, String>();
badMap.put("foo".hashCode(), "bar");
If that's really what your code looks like, just use HashMap<String, String>
instead.
From the docs for Object.hashCode()
(emphasis mine):
The general contract of hashCode is:
- Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application.
- If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.
- It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hash tables.