如何反序列化synchronizedMap和synchronizedList?

时间:2010-01-14 23:48:50

标签: java serialization syntax

这可能只是语法问题(我无法找到它;)

这是要(de)序列化的集合:

private Map<String, Terminal> terminals = Collections.synchronizedMap(new HashMap<String, Terminal>());
private List<Host> hosts = Collections.synchronizedList(new ArrayList<Host>());

这里是序列化:

ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("blah.dmp"));
out.writeObject(synchronizedMap);
out.writeObject(synchronizedList);

现在反序列化,这会引发ClassCastException(显然):

terminals = (HashMap<String, Terminal>) in.readObject();
hosts = (ArrayList<Hosts>) in.readObject();

但以下内容无法编译(以及我尝试过的其他许多变体):

terminals = (Collections.synchronizedMap(new HashMap<String, Terminal>())) in.readObject();
hosts = (Collections.synchronizedList(new ArrayList<Host>())) in.readObject();

2 个答案:

答案 0 :(得分:3)

这个怎么样?

terminals = (Map<String, Terminal>) in.readObject();
hosts = (List<Hosts>) in.readObject();

Map / List包裹的Collections.synchronizedMapCollections.synchronizedList应该被反序列化,而无需重新包装。

答案 1 :(得分:1)

这种语法应该“有效”,但有一个有效的警告:

terminals = (Map<String, Terminal>) in.readObject();

要消除警告并确保100%类型安全,您需要迭代地图的内容,并检查其类型:

Map<?, ?> tmp = (Map<?, ?>) in.readObject();
Map<String, Terminal> copy = new HashMap<String, Terminal>();
for (Map.Entry<?, ?> e : tmp.entrySet()) 
  copy.put((String) e.getKey(), (Terminal) e.getValue());
terminals = Collections.synchronizedMap(copy);