I\'m using a HashMap: byte[] key and String value. But I realize that even I put the same object (same byte array and same string value) by using
myList.put(
NOTE: This is an extremely hack-y way of making an array or a string, a key in a HashMap, without overriding either the equals() or the hashCode() methods. I'll include the answer in a generic way, so readers can get the idea and implement as per their requirements.
Say, I have two numbers, n and r. I want a key-value pair with [n,r] as the key, and (n+r) as the value.
Map, Integer> map = new HashMap, Integer>();
List key = Arrays.asList(n, r);
if( map.containsKey(key) )
return map.get(key);
What if the map did not contain the key?
map.put(Collections.unmodifiableList(Arrays.asList(n, r)), (n+r));
The unmodifiable part (without going into any further depth), ensures that the key cannot change the hash code.
Now, map.containsKey(key) will be true.
Note: This is not a good way to do it. It is just a workaround.