我使用以下代码在我的PC应用程序上序列化HashMap:
private void serialize(HashMap map2write, String name_ser)
{// serializes fphlist into .ser file called name_ser
FileOutputStream fileOut = null;
try {
fileOut = new FileOutputStream(project_dir + "/" + name_ser + ".ser");
} catch (FileNotFoundException ex) {
Logger.getLogger(AdminConsoleUI.class.getName()).log(Level.SEVERE, null, ex);
}
ObjectOutputStream out;
try {
out = new ObjectOutputStream(fileOut);
out.writeObject(map2write);
out.reset();
out.flush();
out.close();
fileOut.close();
} catch (IOException ex) {
Logger.getLogger(AdminConsoleUI.class.getName()).log(Level.SEVERE, null, ex);
}
}
然后我使用以下代码在我的Android应用程序中对其进行反序列化:
private HashMap deserialize_Map(String fn)
{// deserializes fn into HashMap
HashMap hm = new HashMap();
try
{
FileInputStream fileIn = new FileInputStream(project_dir + "/" + fn + ".ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
hm = (HashMap) in.readObject();
in.close();
fileIn.close();
}catch(IOException i)
{
Log.e("MYAPP", "exception", i);
return null;
}catch(ClassNotFoundException c)
{
Log.e("MYAPP", "exception", c);
return null;
}catch(ClassCastException ex)
{
Log.e("MYAPP", "exception", ex);
return null;
}
return hm;
}
最后,我面临两个问题.
1)反序列化需要很长时间.它包含大约数千个键,这是正常的吗?是否有更有效的序列化方法来解决这个问题?
2)反序列化后,我得到的哈希映射占用了它最初在VM上占用的大小的两倍,当我在调试器中检查它时,它在最初应该包含的键值之间有很多空条目.但是,它们不是null键,而只是null,我无法查看它们内部的内容.我在Eclipse中调试.为什么会这样?