【问题标题】:Object Cannot Be Cast to ArrayList对象无法转换为 ArrayList
【发布时间】:2014-12-19 00:51:55
【问题描述】:

我在从 Java 文件中读取数组列表时遇到了一些问题。

我有一个实现 Serializable 的“用户”类,所以当我去保存这些用户的 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();
}

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

谢谢。

【问题讨论】:

  • "Has anyone has similar problems" -- 你的程序中有一个错误,我们都经历过。您还需要展示如何序列化数据,因为您的反序列化不是以与您的序列化对称的方式完成的。看起来您正在将数据序列化为用户对象,然后尝试将其作为 ArrayList 读取,但事实并非如此。
  • 请提供您如何序列化/存储对象的示例代码

标签: java serialization arraylist classcastexception


【解决方案1】:

如果您想从流中反序列化 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();
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-04-28
    • 2020-10-29
    • 1970-01-01
    • 2013-10-16
    • 1970-01-01
    • 1970-01-01
    • 2012-08-22
    • 2012-04-25
    相关资源
    最近更新 更多