Using a byte array as Map key

arrays, hashmap, java

Solution

The problem is that `byte[]` uses object identity for `equals` and `hashCode`, so that

byte[] b1 = {1, 2, 3}
byte[] b2 = {1, 2, 3}

will not match in a `HashMap`. I see three options:

- Wrapping in a `String`, but then you have to be careful about encoding issues (you need to make certain that the byte -> String -> byte gives you the same bytes).

- Use `List<Byte>` (can be expensive in memory).

- Do your own wrapping class, writing `hashCode` and `equals` to use the contents of the byte array.

Problem

Do you see any problem with using a byte array as Map key? I could also do `new String(byte[])` and hash by `String` but it is more straightforward to use `byte[]`.

Original source