HashMap with byte array and String value - containsKey () not working

I use the HashMap: byte [] key and the String value. But I understand that even I put the same object (the same byte array and the same string value) using

myList.put(TheSameByteArray, TheSameStringValue) 

in HashMap, the table still inserts a new object with another HashMapEntry. Then the containsKey () function cannot work.

Can someone explain this to me? How can i fix this? Thank you (Android Java)

 @Override public boolean containsKey(Object key) { if (key == null) { return entryForNullKey != null; } int hash = Collections.secondaryHash(key); HashMapEntry<K, V>[] tab = table; for (HashMapEntry<K, V> e = tab[hash & (tab.length - 1)]; e != null; e = e.next) { K eKey = e.key; if (eKey == key || (e.hash == hash && key.equals(eKey))) { return true; } } return false; } 
+4
source share
3 answers

A byte[] (or any array) cannot function normally as a key in HashMap , since arrays do not override equals , therefore two arrays will be considered equal only if they refer to the same object.

You will have to wrap your byte[] in some kind of custom class that overrides hashCode and equals , and use this custom class as the key to your HashMap.

+5
source

Adding a clear answer to Eran, since byte [] or any array does not override hashcode and equals (it uses the default methods of the Object class), you can always wrap around a String object that takes byte [] as a constructor argument. Not only string forms form good keys in Map, they are also immutable (operations on a map based on Hash are faster)

http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#String (byte [])

+1
source

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.

+1
source

All Articles