首页>代码>effective_java书籍配套源码>/effective_java配套源码/examples/Chapter10/Item55/StringList.java
// StringList with a reasonable custom serialized form - Page 221

import java.io.*;

public class StringList implements Serializable {
    private transient int size   = 0;
    private transient Entry head = null;

    // No longer Serializable!
    private static class Entry {
        String data;
        Entry  next;
        Entry  previous;
    }

    // Appends the specified string to the list
    public void add(String s) {
        Entry e = new Entry();
        e.data = s;
        e.next = head;
        if (head != null)
            head.previous = e;
        head = e;
    }

    public String toString() {
        StringBuffer b = new StringBuffer();
        for (Entry e=head; e!=null; e = e.next) {
            b.append(e.data);
            b.append(" ");
        }
        return b.toString();
    }

    /**
     * Serialize this <tt>StringList</tt> instance.
     *
     * @serialData The size of the list (the number of strings
     * it contains) is emitted (<tt>int</tt>), followed by all of
     * its elements (each a <tt>String</tt>), in the proper
     * sequence.
     */
    private void writeObject(ObjectOutputStream s)
            throws IOException {
        s.defaultWriteObject();
        s.writeInt(size);

        // Write out all elements in the proper order.
        for (Entry e = head; e != null; e = e.next)
            s.writeObject(e.data);
    }

    private void readObject(ObjectInputStream s)
            throws IOException, ClassNotFoundException {
        s.defaultReadObject();
        int size = s.readInt();

        // Read in all elements and insert them in list
        for (int i = 0; i < size; i++)
            add((String)s.readObject());
    }

    // ... // Remainder omitted
}
最近下载更多
湮灭圣者  LV1 1月20日
大隐隐于市  LV2 2021年7月2日
有理想的中年人  LV1 2021年3月16日
水木山  LV1 2021年3月10日
sddyzm  LV7 2020年9月4日
ttxng1  LV1 2020年5月28日
尔丫垚  LV1 2020年5月25日
wsk588  LV26 2020年1月15日
wwslu1317  LV1 2019年12月23日
hepingzhe114  LV1 2019年9月25日
最近浏览更多
湮灭圣者  LV1 1月20日
15575564465  LV1 2023年9月14日
朱俪的邮件及存储  LV8 2023年3月22日
绝对零度  LV2 2022年8月2日
你脚上银铃响了  LV1 2021年10月27日
大隐隐于市  LV2 2021年7月2日
916403064  LV2 2021年6月13日
smile soft 2021年4月28日
暂无贡献等级
有理想的中年人  LV1 2021年3月16日
水木山  LV1 2021年3月10日
顶部 客服 微信二维码 底部
>扫描二维码关注最代码为好友扫描二维码关注最代码为好友