NOTE. This is an extremely efficient way to create an array or string, a key in a HashMap, without overriding the equals () or hashCode () methods. I will include the answer in a general way so that readers can get an idea and implement in accordance with their requirements.
Say I have two numbers, n and r . I want the key to be a key-value pair with [n,r] , and (n+r) value.
Map<List<Integer>, Integer> map = new HashMap<List<Integer>, Integer>(); List<Integer> key = Arrays.asList(n, r); if( map.containsKey(key) ) return map.get(key);
What to do if there was no key on the card?
map.put(Collections.unmodifiableList(Arrays.asList(n, r)), (n+r));
The unmodifiable part (without going into 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 this. This is just a workaround.
source share