JDK-6750650 : java.util.HashMap.keySet() returns a non-serializable (Abstract) Set
  • Type: Enhancement
  • Component: core-libs
  • Sub-Component: java.util:collections
  • Affected Version: 6u10
  • Priority: P4
  • Status: Closed
  • Resolution: Not an Issue
  • OS: windows_xp
  • CPU: x86
  • Submitted: 2008-09-19
  • Updated: 2021-03-03
  • Resolved: 2010-08-26
Related Reports
Relates :  
Relates :  
Relates :  
Description
A DESCRIPTION OF THE REQUEST :
I'm not sure if this is against the spec, but it's certainly annoying...

The following code snippet returns HashMap$KeySet, which is a subclass of AbstractSet, and thus not Serializable.The parent HashMap object is Serializable though.

{
    Set set = map.keySet();
}

JUSTIFICATION :
Main use case for this is if one wants to store a keySet in a J2EE HttpSession - I could store the HashMap, so why can't I store it's keySet()?

EXPECTED VERSUS ACTUAL BEHAVIOR :
EXPECTED -
HashMap$KeySet implements Serializable
ACTUAL -
HashMap$KeySet extends AbstractSet
(and doesn't implement Serializable)

---------- BEGIN SOURCE ----------
See above - no other need for code example
---------- END SOURCE ----------

CUSTOMER SUBMITTED WORKAROUND :
new HashSet( map.keySet() );

Obviously this isn't a good example for performance / efficiency.

Comments
EVALUATION Yes, you can serialize a copy of a HashMap's keyset, but you can't serialize the keyset itself, because of its link back to the original map. This isn't a bug. I'm not sure what value there is in adding to the documentation, since the correct way to do this is suggested in the report.
26-08-2010

WORK AROUND Instead of trying to serialize "map.keySet()", serialize "new HashSet(map.keySet())".
22-09-2008