对象无法转换为ArrayList

时间:2014-12-19 00:51:55

标签: java serialization arraylist classcastexception

我在从Java文件中读取arraylist时遇到了一些麻烦。

我有一个实现Serializable的“User”类,所以当我去保存这些用户的ArrayList时,它似乎工作正常 - 但是当我尝试阅读它们时,它是一个不同的故事。

ava.lang.ClassCastException:无法将用户强制转换为java.util.ArrayList

我阅读的守则如下......

 private List<User> userList = new ArrayList<User>();

public void readList() throws FileNotFoundException, IOException, ClassNotFoundException
{
    System.out.println("Trying to read list..");
    FileInputStream fis = new FileInputStream("userList.txt");
    ObjectInputStream ois = new ObjectInputStream(fis);
    System.out.println("Created Streams....");
    userList = ((ArrayList<User>)ois.readObject());
    ois.close();
}

有没有人有类似的问题或知道如何帮助我?

感谢。

1 个答案:

答案 0 :(得分:0)

如果要从流中反序列化ArrayList,则必须确保将ArrayList序列化到流中。您序列化User对象的方式,您需要反序列化它们:

private List<User> userList;

public void readList() throws FileNotFoundException, IOException, ClassNotFoundException {
    System.out.println("Trying to read list..");
    this.userList = new ArrayList<User>();
    FileInputStream fis = new FileInputStream("userList.txt");
    try {
        ObjectInputStream ois = new ObjectInputStream(fis);
        System.out.println("Created Streams....");

        // you would want to store this number in your object stream as userList.size()
        int numberOfUsersSerialized = 5;
        for (int i = 0; i < numberOfUsersSerialized; i++) {
            userList.add((User) ois.readObject());
        }
    } finally {
        fis.close();
    }
}