0
給定一個Java映射,其中的鍵和值都是可序列化的,我希望能夠序列化鍵 - 值對。有沒有任何有效的方法,給定的關鍵我可以檢索鍵值對作爲一個對象和序列化?我已經看到了map類的entrySet()方法,但我不喜歡兩次搜索這個對。訪問映射的鍵值對作爲對象
給定一個Java映射,其中的鍵和值都是可序列化的,我希望能夠序列化鍵 - 值對。有沒有任何有效的方法,給定的關鍵我可以檢索鍵值對作爲一個對象和序列化?我已經看到了map類的entrySet()方法,但我不喜歡兩次搜索這個對。訪問映射的鍵值對作爲對象
地圖不提供這樣的方法是可序列化。但是,還有什麼可以做的就可以了,通過擴展Map實現爲例 - HashMap<K,V>
和實施這樣的方法一樣 -
Map<K,V> map = new HashMap<K,V>(){
public Entry<K,V> get(Object key) { // overloading get method in subclass
if (key == null)
return getForNullKey();
int hash = hash(key.hashCode());
for (Entry<K,V> e = table[indexFor(hash, table.length)];
e != null;
e = e.next) {
Object k;
if (e.hash == hash && ((k = e.key) == key || key.equals(k)))
return e;
}
return null;
}
private Entry<K,V> getForNullKey() {
for (Entry<K,V> e = table[0]; e != null; e = e.next) {
if (e.key == null)
return e;
}
return null;
}};
...
Map.Entry<K,V> entry1 = map.get(key);// invoking Entry<K,V> get(Object key)
可以序列它作爲一個陣列:
Object obj = new Object[] {key, value}
OBJ只要鍵和值是可序列化