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(TheSameByteArray, TheSameStringValue)
into HashMap, the table still inserts a new object with different HashMapEntry. Then function containsKey() cannot work.
Can someone explains this for me? How can I fix this? Thanks. (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;
}
String is as a key of the HashMap When you create a HashMap object and try to store a key-value pair in it, while storing, a hash code of the given key is calculated and its value is placed at the position represented by the resultant hash code of the key.
get() method of HashMap class is used to retrieve or fetch the value mapped by a particular key mentioned in the parameter. It returns NULL when the map contains no such mapping for the key.
In a HashMap, keys and values can be added using the HashMap. put() method. We can also convert two arrays containing keys and values into a HashMap with respective keys and values.
put() method of HashMap is used to insert a mapping into a map. This means we can insert a specific key and the value it is mapping to into a particular map. If an existing key is passed then the previous value gets replaced by the new value. If a new pair is passed, then the pair gets inserted as a whole.
A byte[]
(or any array) can't work properly as a key in a HashMap
, since arrays don't override equals
, so two arrays will be considered equal only if they refer to the same object.
You'll have to wrap your byte[]
in some custom class that overrides hashCode
and equals
, and use that custom class as the key to your HashMap.
Adding to Eran's clear answer,Since byte[] or any array doesnt override hashcode and equals(it uses the default methods of Object class ),you can always wrap around a String Object which takes byte[] as constructor argument.Not only does String form good keys in Map,they are immutable too(the operations in a Hash based map are faster)
http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#String(byte[])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With