Sobes.tech
Junior — Middle

Why is it dangerous to use a byte array as a key in a HashMap data structure?

sobes.tech AI

Answer from AI

In Java, arrays (for example, byte[]) do not override the equals() and hashCode() methods inherited from Object. This means that when using a byte array as a key in a HashMap, the key comparison will be based on reference equality, not content equality. As a result, even two arrays with identical bytes will be considered different keys, leading to unexpected behavior — for example, being unable to find a value by a logically matching key.

To avoid this problem, it is better to use wrappers that correctly implement equals() and hashCode(), such as the ByteBuffer class, or use strings (String) if appropriate, or implement a custom key class with proper comparison logic.

Example of the problem:

byte[] key1 = {1, 2, 3};
byte[] key2 = {1, 2, 3};

Map<byte[], String> map = new HashMap<>();
map.put(key1, "value");

System.out.println(map.get(key2)); // null, even though key1 and key2 contain the same bytes

Correct approach — use, for example, ByteBuffer:

ByteBuffer key1 = ByteBuffer.wrap(new byte[]{1, 2, 3});
ByteBuffer key2 = ByteBuffer.wrap(new byte[]{1, 2, 3});

Map<ByteBuffer, String> map = new HashMap<>();
map.put(key1, "value");

System.out.println(map.get(key2)); // "value"