简体   繁体   English

将Map的键值对作为对象访问

[英]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. 给定一个Java Map,其中键和值都是可序列化的,我希望能够序列化键值对。 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. 我已经看到了map类的entrySet()方法,但我不想两次搜索该对。

You can serialize it as an array: 您可以将其序列化为数组:

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

obj is Serializable as soon as key and value are Serializable 只要键和值是Serializable,obj就是Serializable

map does not provides such method. map没有提供这样的方法。 But what Still you can do you can, by extending the Map implementation as example - HashMap<K,V> and implement such method like - 但是,你还能做什么,通过扩展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.

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