问题
I'm often using java serialization, which is very usefull to store a complete object hierarchy.
When trying to serialize a SetMultimap, I got an exception saying that that AbstractMultimap.WrappedSet is not serializable.
How do guava users workaround with this problem?
Thanks in advance,
回答1:
The views of elements of a multimap (such as the collections returned from get
methods, the asMap
view, etc.) are intentionally not serializable. However, it isn't true that a SetMultimap
implementation would not be serializable because of that. All implementations of SetMultimap
that Guava provides are in fact serializable... it's just the partial view collections for them that are not.
If you need to serialize one of these collections, you should explicitly copy it to a normal collection:
Set<Foo> foo = Sets.newHashSet(multimap.get(someKey));
回答2:
Edit So looking at the source of AbstractMultimap
, the Map
that is returned is an AsMap
or SortedAsMap
, neither of which are serializable. I would suggest creating a new HashMap
and use the putAll
method passing in the Multimap.asMap()
result. HashMap
is serializable.
HashMap myMap = new HashMap();
myMap.putAll(myMultimap.asMap());
来源:https://stackoverflow.com/questions/8488394/guava-setmultimap-not-serializable-due-to-not-serializable-wrappedset