一、JedisByteHashMap
JedisByteHashMap是Jedis中實作存儲鍵和值均為byte[]位元組數組的Map集合類,它利用HashMap作為鍵-值對實際存儲集合,對Map中的方法進行重寫來達到Jedis需要的存儲鍵-值對均為位元組數組的需要。該類是非線程安全的。
二、源碼分析
該類實作上沒什麼複雜的地方,個人覺得比較有趣的一個實作是對鍵進行了包裝。HashMap在實作鍵值對映射時,會調用鍵的equals和hashCode方法,byte[]數組這兩個方法均是從Object繼承而來,顯然不滿足需求,于是JedisByteHashMap中的内部類對byte[]數組進行了簡單的包裝來滿足需求,這實際上用到了擴充卡的設計思想。
private static final class ByteArrayWrapper {
private final byte[] data;
public ByteArrayWrapper(byte[] data) {
if (data == null) {
throw new NullPointerException();
}
this.data = data;
}
public boolean equals(Object other) {
if (!(other instanceof ByteArrayWrapper)) {
return false;
}
return Arrays.equals(data, ((ByteArrayWrapper) other).data);
}
public int hashCode() {
return Arrays.hashCode(data);
}
}
同樣為了實作entrySet方法,傳回鍵和值均為位元組數組的Entry對象,JedisByteHashMap也實作了對Entry進行包裝的内部類
private static final class JedisByteEntry implements Entry<byte[], byte[]> {
private byte[] value;
private byte[] key;
public JedisByteEntry(byte[] key, byte[] value) {
this.key = key;
this.value = value;
}
public byte[] getKey() {
return this.key;
}
public byte[] getValue() {
return this.value;
}
public byte[] setValue(byte[] value) {
this.value = value;
return value;
}
}```