Using byte[] as a key in a HashMapdoesn’t work the way you might expect — and it’s all because of how arrays handle equals() and hashCode() in Java.
🚫 Why byte[] doesn’t work as a HashMap key:
1. Default equals() is identity-based
When you use byte[] as a key, it inherits equals() from Object:
byte[] a = {1, 2, 3};
byte[] b = {1, 2, 3};
System.out.println(a.equals(b)); // false ❌
Even though the contents are the same, the two arrays are different objects, so:
equals()returns false,hashCode()is based on memory address, not content.
2. HashMap uses equals() and hashCode()
So when you do:
map.put(a, "value");
map.get(b); // returns null ❌
It doesn’t find b even though it “looks” like a, because the keys are not considered equal.
✅ Correct way to use byte arrays as keys:
Option 1: Use java.util.Arrays helpers
Map<List<Byte>, String> map = new HashMap<>();
map.put(Arrays.asList((byte)1, (byte)2), "value");
✅ List<Byte> implements proper equals() and hashCode().
Or, for more performance:
Option 2: Wrap in a custom class
class ByteArrayKey {
private final byte[] data;
public ByteArrayKey(byte[] data) {
this.data = data;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof ByteArrayKey)) return false;
ByteArrayKey other = (ByteArrayKey) o;
return Arrays.equals(this.data, other.data);
}
@Override
public int hashCode() {
return Arrays.hashCode(data);
}
}
Now you can do:
Map<ByteArrayKey, String> map = new HashMap<>();
map.put(new ByteArrayKey(new byte[]{1, 2, 3}), "value");
TL;DR
You can’t use byte[] directly as a HashMap key because:
- It uses reference equality (
==) instead of content equality. - It doesn’t override
hashCode()andequals().
➡️ Wrap it, or use a content-aware structure like List<Byte> or a custom class.