Guava SetMultimap not serializable (due to not serializable WrappedSet)

大城市里の小女人 提交于 2020-01-02 09:57:30

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!