访问Map的键值对作为对象

时间:2014-04-04 11:16:34

标签: java serialization hashmap

给定一个Java Map,其中键和值都是可序列化的,我希望能够序列化键值对。是否有任何有效的方法,给定键我可以检索键值对作为对象并序列化?我已经看过地图类的entrySet()方法,但我不想两次搜索该对。

2 个答案:

答案 0 :(得分:1)

您可以将其序列化为数组:

Object obj = new Object[] {key, value}
一旦key和value为Serializable

obj就是Serializable

答案 1 :(得分:1)

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) 
相关问题