[英]HashMap Deserialization Issues in Android
我使用以下代码在我的PC应用程序上序列化HashMap:
private void serialize(HashMap<Integer, Integer> 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<Integer,Integer> deserialize_Map(String fn)
{// deserializes fn into HashMap
HashMap<Integer,Integer> hm = new HashMap<Integer,Integer>();
try
{
FileInputStream fileIn = new FileInputStream(project_dir + "/" + fn + ".ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
hm = (HashMap<Integer,Integer>) 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中调试。 为什么会这样?
您是否尝试将HashMap序列化为JSON对象? Android对从文件反序列化JSON有很好的支持。
1)VM大小中“普通”HashMap的大小是多少? 对于那个问题,我认为这不是另一种解决方案(如果有人向我们展示)。 您可以尝试共享sqlite或其他东西。 如果您想提出您想要解决的问题,我们可以提出可以加快工作速度的技术
更新
如果你知道大小HashMap<Integer,Integer> hm = new HashMap<Integer,Integer>(SIZE*2);
你可以尝试在初始时按照你的建议初始化Map HashMap<Integer,Integer> hm = new HashMap<Integer,Integer>(SIZE*2);
从这里开始
HashMap的一个实例有两个影响其性能的参数:初始容量和负载因子。 容量是哈希表中的桶数,初始容量只是创建哈希表时的容量。 加载因子是在自动增加容量之前允许哈希表获取的完整程度的度量。 当哈希表中的条目数超过加载因子和当前容量的乘积时,通过调用rehash方法,容量大致加倍
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.