2

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,

Martin Pernollet
  • 2,285
  • 1
  • 28
  • 39

2 Answers2

7

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));
ColinD
  • 108,630
  • 30
  • 201
  • 202
0

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());
John B
  • 32,493
  • 6
  • 77
  • 98
  • Actually putAll(...) copies the content into the Set created by the multimap itself. Moreover, whatever Set implementation is used, it is always wrapped into a WrappedCollection which is definitly not serializable. Since unfortunately HashMultimap is final, one can't override it, so I started copying the code HashMultimap to modify it, but WrappedCollection has some references to private var that can't be reached... So I just added an enhancement query in http://code.google.com/p/guava-libraries/issues/detail?id=615 – Martin Pernollet Dec 13 '11 at 14:20
  • I didn't say `HashMultimap` but `HashMap`. – John B Dec 13 '11 at 14:46
  • The values in your HashMap will be the Sets created by the multimap, which are not serializable. – Louis Wasserman Dec 13 '11 at 19:24