【发布时间】:2015-09-05 11:20:18
【问题描述】:
我想将 ArrayList 写入文件,然后再次读取。该列表将保存 Integer 对象。序列化似乎工作正常,但我在反序列化时遇到了麻烦。更具体地说,我无法正确选择。
序列化:
ObjectOutputStream ou =
new ObjectOutputStream(new FileOutputStream(new File("load.dat")));
ArrayList<Integer> ouList = new ArrayList<>();
ou.writeObject(ouList);
ou.close();
derserization:
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 当我将它投射到它时?提前感谢您的帮助。
【问题讨论】:
-
删除 in.readObject() 周围的括号会发生什么。试试这个 ArrayList
inList = (ArrayList )in.readObject(); -
从 Object 转换泛型会导致未经检查的转换,删除泛型可解决未经检查的警告,但如果您需要 rawtype 忽略警告,请按照建议使用 try/catch
标签: java serialization arraylist casting deserialization