Search code examples
javahashmaparrays

Using a byte array as Map key


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[].


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:

    1. 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).
    2. Use List<Byte> (can be expensive in memory).
    3. Do your own wrapping class, writing hashCode and equals to use the contents of the byte array.