[英]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.