如何序列化对象的ArrayList? [英] How to serialize ArrayList of objects?

查看:96
本文介绍了如何序列化对象的ArrayList?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想序列化 Item 的数组列表,但是它不起作用....

I want to serialize an arraylist of Item but it doesn't work....

我的 Item 类扩展了 Stuff 类,并且具有一些子类.

my Item class extends Stuff class and has some subclasses.

我所有的类都实现Serilalizable.

all of my classes implement Serilalizable.

我有这部分:

try{
// Serialize data object to a file
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("MyData.ser"));
out.writeObject(myData);
out.close();

// Serialize data object to a byte array
ByteArrayOutputStream bos = new ByteArrayOutputStream() ;
out = new ObjectOutputStream(bos) ;
out.writeObject(myData);
out.close();

// Get the bytes of the serialized object
byte[] buf = bos.toByteArray();
} catch (IOException e) {
}

我的课程:

public class Stuff implements Serializeable{
....
some protected fields
.
.
}

public class Item extends Stuff implements Serializable{
...
..
.
} and some subclasses of Item:

public class FirstItem extends Item implements Serializable{
...
}

public class SecondItem extends Item implements Serializable{
...
} ... I want to serialize an object contains ArrayList of <Item> that has objects of Item's subclasses (FirstItem,SecondItem,...)

我认为信息足够...

这只是一个小错误,现在可以正常使用了... 我为我的愚蠢问题感到抱歉.

it's just a little mistake and now works correctly... I'm sorry for my stupid question.

谢谢您的回答.

推荐答案

您可以像这样序列化ArrayList的类

You can serialize class of ArrayList like this

public class MyData implements Serializable {

    private long id;
    private String title;
    private ArrayList<String> tags;
    ...

    public String getTitle() {
    }
}

并创建可序列化的

    ArrayList<MyData> myData = new ArrayList<MyData>();

try{
    // Serialize data object to a file
    ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("MyData.ser"));
    out.writeObject(myData);
    out.close();

    // Serialize data object to a byte array
    ByteArrayOutputStream bos = new ByteArrayOutputStream() ;
    out = new ObjectOutputStream(bos) ;
    out.writeObject(myData);
    out.close();

    // Get the bytes of the serialized object
    byte[] buf = bos.toByteArray();
} catch (IOException e) {
}

这篇关于如何序列化对象的ArrayList?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆