HashMap中有很多变量都是transient的,不会被序列化。我想知道序列化时写入的是哪个字段?我发现有一个table变量是transient的,结果在反序列化的时候,它竟然有值,请解释一下。测试代码: 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);

解决方案 »

  1.   

    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];