【发布时间】:2019-05-04 12:55:09
【问题描述】:
首先我创建项目 A。然后我将项目 A 添加到列表 A。然后我将项目 A 序列化到一个文件中,然后我从同一个文件中读取项目 A。最后,我从列表 A 中找到读取的项目 B。在列表 A 中定位项目 B 失败。 println 语句的结果是-1。我的问题是为什么?
public class ListTest {
public static void main(String[] args) {
Item a = new Item("a");
List<Item> listA = new ArrayList<Item>();
listA.add(a);
try (FileOutputStream fos = new FileOutputStream(new File("text.dat"));
ObjectOutputStream oos = new ObjectOutputStream(fos)) {
oos.writeObject(a);
try (FileInputStream fis = new FileInputStream(new File("text.dat"));
ObjectInputStream ois = new ObjectInputStream(fis)) {
Item b = (Item) ois.readObject();
System.out.println(listA.indexOf(b));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
}
}
}
** 编辑 1 **
商品的代码在哪里。
public class Item implements Serializable {
private static final long serialVersionUID = 1L;
private String mName;
public Item(String name) {
mName = name;
}
public String getName() {
return mName;
}
public void setName(String name) {
mName = name;
}
}
【问题讨论】:
-
Item是否实现了Serializable? -
是的,确实如此。我添加了编辑 1 的代码。
标签: java file arraylist serialization