Actually, I can't see anything wrong in the approach suggested in the linked answer. They say you have to wrap your byte array into some class having predictable and consistent hashCode()
and equals()
implementations. Someone suggests using String
or ByteBuffer
, but that would definitely be a hack and may screw up at some point. This simple wrapper may be enough (note that I made a defensive copy of the input bytes to prevent modifications that will alter hashCode()
and equals()
computations: key in maps must be immutable):
class HashtableByteArray {
private final byte[] data;
public HashtableByteArray(byte[] data) {
this.data = Arrays.copyOf(data, data.length);
}
public int hashCode() {
return Arrays.hashCode(data);
}
public boolean equals(Object other) {
return other instanceof HashtableByteArray
&& Arrays.equals(data, ((HashtableByteArray) other).data);
}
}
This sample relies heavily on the utils in the Arrays
class, but you can certainly build your version with optimized hashCode() and equals() that better suite your needs.