Map的keySet方法序列化BUG问题及其解决方法

Map的keySet在进行序列化时,报错:java.io.NotSerializableException: java.util.HashMap$KeySet。这个异常可以再oracle的官网: http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4756277中查到原因,为了方便日后测试序列化问题,给出序列化的测试类。
序列化的测试类:
import java.io.ByteArrayOutputStream;
import java.io.ObjectOutputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by IntelliJ IDEA.
 * User: dragon
 * Date: 12-8-20
 * Time: 上午11:04
 * 序列化测试类
 */
public class MapCollectionSerializeTest {

    private static void trySerialize (Object o) {
        try {
            ObjectOutputStream stream
                = new ObjectOutputStream(new ByteArrayOutputStream());
            System.out.print("Trying to serialize " + o + "...");
            stream.writeObject(o);
            stream.flush();
            System.out.println("done");
        }
        catch (Exception e) {
            System.out.print("failed: ");
            e.printStackTrace();
        }
    }

    // ----------------------------------------------------------------------
    // Entry point

    public static void main (String[] args) {

        Map map = new HashMap();
        map.put("one", "one");
        map.put("two", "two");
        map.put("three", "three");

        System.out.println("keySet():");
        trySerialize(map.keySet());
        System.out.println("entrySet():");
        trySerialize(map.entrySet());
        System.out.println("values():");
        trySerialize(map.values());

    }
}


解决方法:
Set set = new HashSet(map.keySet());

你可能感兴趣的:(序列化问题,Map keySet())