简体   繁体   中英

Access a Map's key-value pair as an object

Given a Java Map in which both the key and the value are serializable, I want to be able to serialize the key-value pair. Is there any efficient way that given the key I could retrieve the key-value pair as an object and serialize that? I've seen the entrySet() method for the map class but I don't like to search for the pair twice.

You can serialize it as an array:

Object obj = new Object[] {key, value}

obj is Serializable as soon as key and value are Serializable

map does not provides such method. But what Still you can do you can, by extending the Map implementation as example - HashMap<K,V> and implement such method like -

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) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM