when i use hashcode string as key in HashMap.
You should not use the hash code as a key. Hash codes are not intended to be unique - it completely allowed two unequal values ββto have the same hash code. You must use the string as a key. Then the map will first compare the hash codes (quickly narrow down the candidates), and then compare with equals for true equality of strings.
Of course, assuming your code is really the way your question does, for example
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 this is really your code, just use HashMap<String, String> .
From the docs for Object.hashCode() (my attention):
General hashCode contract:
- Whenever it is called by the same object more than once during the execution of a Java application, the hashCode method must consistently return the same integer if the information used in equal comparisons with the object does not change. This integer should not remain consistent with one execution of the application on another execution of the same application.
- If two objects are equal in accordance with the equals (Object) method, then calling the hashCode method for each of the two objects should lead to the same integer result.
- It is not required that if two objects are unequal according to the equals method (java.lang.Object), then calling the hashCode method for each of the two objects must produce different integer results. However, the programmer should be aware that creating separate integer results for unequal objects can improve the performance of hash tables.
source share