java - 需要帮助来理解 Java 中 ArrayList 的反序列化

标签 java serialization arraylist casting deserialization

我想将 ArrayList 写入文件,然后再次读回。该列表将保存整数对象。序列化似乎工作正常,但我在反序列化时遇到问题。更具体地说,我可以正确选角。

序列化:

ObjectOutputStream ou =
    new ObjectOutputStream(new FileOutputStream(new File("load.dat")));

ArrayList<Integer> ouList = new ArrayList<>();
ou.writeObject(ouList);
ou.close();

反序列化:

ObjectInputStream in =
    new ObjectInputStream(new FileInputStrean("load.dat"));
ArrayList<Integer> inList = (ArrayList<Integer>)(in.readObject();
in.close();

当我编译时,我收到未经检查和不安全的警告。我使用 Xclint:unchecked 重新编译并收到以下消息:

warning: [unchecked] unchecked cast
    ArrayList<Integer> inList = (ArrayList<Integer>)(in.readObject());
                                                    ^
  required: ArrayList<Integer>
  found:    Object

我发现这有点令人困惑:转换不是应该将对象转换为数组列表吗?当我将其转换为 ArrayList 时,为什么它需要 ArrayList?预先感谢您的帮助。

最佳答案

它告诉您编译器无法保证转换在运行时会成功 - 它可能会产生 ClassCastException

通常您可以使用 instanceof 检查之前的类型以防止出现此警告,例如:

if (x instanceof ArrayList) {
    ArrayList y = (ArrayList) x; // No warning here 
}

不幸的是,instanceof 无法在运行时检查泛型参数,因此您将无法安全地执行此操作。您所能做的就是抑制警告。

但是,如果您确实想确定集合的类型,那么您可以通过以下方式更改代码:

public class ArrayListOfIntegers extends ArrayList<Integer> {}

...

// writing:
ArrayListOfIntegers ouList = new ArrayListOfIntegers();
...
// reading:
ArrayListOfIntegers inList;
Object readData = in.readObject();
if (readData instanceof ArrayListOfIntegers) {
    inList = (ArrayListOfIntegers) readData;
} else {
    throw new RuntimeException("...");
}

关于java - 需要帮助来理解 Java 中 ArrayList 的反序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30938747/

相关文章:

java - 链式方法设计

generics - protobuf-net 可以序列化这种接口(interface)和泛型集合的组合吗?

java - 无法将 double 转换为 double [] 错误

java - 无法让 java 流与 arraylist 一起工作

java - 如何输出数组列表中的一个元素?

Java : how to call methods with the same name in different objects instantiated from different classes?

java - Java 中的 WebSocket 编程 : client server communication issue

javascript - 如何有效地序列化 64 位 float 以便字节数组保留自然数字顺序?

Java - 从文件中读取松散结构的数据

java - 如何搜索 mp3 文件目录并按艺术家筛选结果?