当前位置: 代码迷 >> J2SE >> java HashMap中写下writeObject时写入的什么
  详细解决方案

java HashMap中写下writeObject时写入的什么

热度:2588   发布时间:2013-02-25 00:00:00.0
java HashMap中写入writeObject时写入的什么
HashMap中有很多变量都是transient的,不会被序列化。我想知道序列化时写入的是哪个字段?

我发现有一个table变量是transient的,结果在反序列化的时候,它竟然有值,请解释一下。

测试代码:
Java code
        HashMap<String, Object> map = new HashMap<String, Object>();        map.put("1", new Date());        ByteArrayOutputStream bo = new ByteArrayOutputStream();        ObjectOutputStream oo = new ObjectOutputStream(bo);        oo.writeObject(map);        ByteArrayInputStream bi = new ByteArrayInputStream(bo.toByteArray());        ObjectInputStream oi = new ObjectInputStream(bi);        Object obj = oi.readObject();                //这个地方设置断点,发现obj的table不为空。。        System.out.println(obj);


------解决方案--------------------------------------------------------
HashMap 是自行管理序列化的,你可以看看它提供了两个函数:
writeObject(java.io.ObjectOutputStream s) // 序列化时调用
readObject(java.io.ObjectInputStream s) // 反序列化时调用

HashMap会在readObject中,将所需要的对象重新初始化回来,比如:

// Read in the threshold, loadfactor, and any hidden stuff
s.defaultReadObject();

// Read in number of buckets and allocate the bucket array;
int numBuckets = s.readInt();

table = new Entry[numBuckets];
  相关解决方案