I am using boolean arrays as keys for a HashMap. But the problem is HashMap fails to get the keys when a different array is passed as key, although the elements are same. (As they are different objects).
How can I make it work with arrays as keys ? Here is the code :
public class main { public static HashMap<boolean[], Integer> h; public static void main(String[] args){ boolean[] a = {false, false}; h = new HashMap<boolean[], Integer>(); h.put(a, 1); if(h.containsKey(a)) System.out.println("Found a"); boolean[] t = {false, false}; if(h.containsKey(t)) System.out.println("Found t"); else System.out.println("Couldn't find t"); } }
Both the arrays a
and t
contain the same elements, but HashMap doesn't return anything for t
.
How do I make it work ?
You cannot do it this way. Both t
and a
will have different hashCode()
values because the the java.lang.Array.hashCode()
method is inherited from Object
, which uses the reference to compute the hash-code (default implementation). Hence the hash code for arrays is reference-dependent, which means that you will get a different hash-code value for t
and a
. Furthermore, equals
will not work for the two arrays because that is also based on the reference.
The only way you can do this is to create a custom class that keeps the boolean
array as an internal member. Then you need to override equals
and hashCode
in such a way that ensures that instances that contain arrays with identical values are equal and also have the same hash-code.
An easier option might be to use List<Boolean>
as the key. Per the documentation the hashCode()
implementation for List
is defined as:
int hashCode = 1; Iterator<E> i = list.iterator(); while (i.hasNext()) { E obj = i.next(); hashCode = 31*hashCode + (obj==null ? 0 : obj.hashCode()); }
As you can see, it depends on the values inside your list and not the reference, and so this should work for you.
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