JDK-4501848 : Objects returned by keySet(), entrySet() and values() not Serializable
  • Type: Bug
  • Component: core-libs
  • Sub-Component: java.util
  • Affected Version: 1.3.1
  • Priority: P4
  • Status: Closed
  • Resolution: Not an Issue
  • OS: generic
  • CPU: generic
  • Submitted: 2001-09-11
  • Updated: 2001-09-13
  • Resolved: 2001-09-13
Related Reports
Relates :  

Name: ddT132432			Date: 09/11/2001

java version "1.3.1"
Java(TM) 2 Runtime Environment, Standard Edition (build 1.3.1-b24)
Java HotSpot(TM) Client VM (build 1.3.1-b24, mixed mode)

The methods keySet(), entrySet() and values() return objects that are instances
of anonymous inner classes. These anonymous inner classes do not implement
Serializable, so that the Set objects returned by these methods are not
Serializable. This is inconsistent with the standard JDK collections
implementation classes, which all implement Serializable.

This bug leads to unexpected results, see the example program below.

import java.io.*;
import java.util.*;

public class MyTest {

    public static void main(String[] args) throws Exception {

        Map myMap = new HashMap();

        myMap.put(new Integer(1), "one");
        myMap.put(new Integer(2), "two");

        FileOutputStream fos = new FileOutputStream("test.dat");
        ObjectOutputStream oos = new ObjectOutputStream(fos);

        Set obj = myMap.keySet();   // NOTE: This set is NOT Serializable!
        oos.writeObject(obj);       // Throws an NotSerializableException


(Review ID: 131494) 

WORK AROUND Name: ddT132432 Date: 09/11/2001 Copy the values of the Set returned by keySet(), entrySet() or values() into a new HashSet or TreeSet object: Set obj = new HashSet(myMap.keySet()); ======================================================================

EVALUATION It is almost always incorrect for inner classes to implement Serializable. The semantics violate the principle of least astonishment: serializing the instance of the nested class implicitly serializes its enclosing instance, even though it may be inaccessible. More seriously, it is non-portable. The serialized form is dependent on the details of the compiler's internal representation of nested classes. See page 217 of "Effective Java Programming Language Guide" [Bloch, 2001, Addison-Wesley] for details. ###@###.### 2001-09-12