内部数组序列化的奇怪行为

时间:2015-10-22 00:52:47

标签: java arrays serialization

我想将大量数字序列化到文件中。 所以我决定使用一些包装器对象作为基元数组并在循环中将其序列化。 但是在过程中我遇到了一些有趣的行为:尽管我在内部数组中更改了值,但实际上每次都会序列化第一个副本。 那么,有人可以澄清这种情况或发现我的错误吗? :)

我的基础对象:

public class PortionWrapper implements Serializable{
    private static final long serialVersionUID = -55857686305273843L;
    private long[] portion;

    public PortionWrapper() {   }
    public PortionWrapper(long[] portion) {  this.portion = portion; }

    //--------------------------------------------------
    public long[] getPortion() {             return portion; }
    public void setPortion(long[] portion) { this.portion = portion; }

    @Override
    public String toString() {
        return "Wrapper{ portion=" + Arrays.toString(portion) "}";
    }
}

我的序列化过程:

FileOutputStream fos = new FileOutputStream("sequences/seq.ser")
ObjectOutputStream oos = new ObjectOutputStream(fos);
long[] a1 = {1L, 2L, 3L};
oos.writeObject(new PortionWrapper(a1));
a1[0] = 0;
a1[1] = 0;
a1[2] = 0;
oos.writeObject(new PortionWrapper(a1));
oos.close();

反序列化:

try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("sequences/seq.ser")))
{
    do {
        portionWrapper = (PortionWrapper)ois.readObject();
        System.out.println(portionWrapper);
    } while (true);
} catch (EOFException e) {
}

输出:

PortionWrapper{portion=[1, 2, 3]}
PortionWrapper{portion=[1, 2, 3]}

0 个答案:

没有答案