[英]Access a Map's key-value pair as an object
給定一個Java Map,其中鍵和值都是可序列化的,我希望能夠序列化鍵值對。 是否有任何有效的方法,給定鍵我可以檢索鍵值對作為對象並序列化? 我已經看到了map類的entrySet()方法,但我不想兩次搜索該對。
您可以將其序列化為數組:
Object obj = new Object[] {key, value}
只要鍵和值是Serializable,obj就是Serializable
map沒有提供這樣的方法。 但是,你還能做什么,通過擴展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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.