United StatesChange Country, Oracle Worldwide Web Sites Communities I am a... I want to...
Bug ID: 4501848 Objects returned by keySet(), entrySet() and values() not Serializable
4501848 : Objects returned by keySet(), entrySet() and values() not Serializable

Details
Type:
Bug
Submit Date:
2001-09-11
Status:
Closed
Updated Date:
2001-09-13
Project Name:
JDK
Resolved Date:
2001-09-13
Component:
core-libs
OS:
generic
Sub-Component:
java.util
CPU:
generic
Priority:
P4
Resolution:
Not an Issue
Affected Versions:
1.3.1
Fixed Versions:

Related Reports
Relates:

Sub Tasks

Description

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

        oos.flush();
        oos.close();

        System.out.println("Success!");
    }
}
(Review ID: 131494) 
======================================================================

                                    

Comments
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());
======================================================================
                                     
2004-06-11
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
                                     
2001-09-12



Hardware and Software, Engineered to Work Together