我想将 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/