Middle
Why can't byte[] arrays be used as keys in HashMap?
sobes.tech AI
Answer from AI
Because the standard implementation of equals() for arrays compares them by reference, not by content. HashMap uses the equals() and hashCode() methods to compare keys. If two byte arrays have different contents but the same reference, they are considered equal. If they have the same contents but different references, they are considered not equal.
To correctly use byte[] as a key, it needs to be wrapped in an object that overrides equals() and hashCode() for content comparison. Here's an example of such a wrapper:
// Example implementation of a wrapper
public class ByteArrayWrapper {
private final byte[] data;
public ByteArrayWrapper(byte[] data) {
this.data = data;
}
public byte[] getData() {
return data;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ByteArrayWrapper that = (ByteArrayWrapper) o;
return Arrays.equals(data, that.data);
}
@Override
public int hashCode() {
return Arrays.hashCode(data);
}
}