安卓中HashMap反序列化问题

4

我正在使用以下代码在我的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)在反序列化之后,我得到了一个哈希表,在虚拟机上占用的空间几乎是它最初占用的两倍。当我在调试器中检查它时,其原本应该包含的键值之间有许多空条目。然而,它们不是空键,只是空的,我无法查看其中的内容。我在Eclipse中进行调试。为什么会发生这种情况?
2个回答

3

1)在VM大小中,“正常”HashMap的大小是多少? 我认为没有其他解决方案(如果有,请有人向我们展示)。您可以尝试共享sqlite或其他内容。如果您想合作解决问题,我们可以提出使工作更快的技术。

更新

您可以尝试在初始化时使用大容量初始化Map,如您所建议的,如果您知道大小HashMap<Integer,Integer> hm = new HashMap<Integer,Integer>(SIZE*2);

来自这里的第2点。

HashMap的一个实例具有影响其性能的两个参数:初始容量和负载因子。容量是哈希表中的桶数,初始容量只是创建哈希表时的容量。负载因子是哈希表允许填满之前的度量。当哈希表中的条目数超过负载因子和当前容量的乘积时,通过调用rehash方法大致将容量加倍。


谢谢,这真的很有帮助。我从来不知道我可以玩HashMap参数。在初始化期间指定负载因子和容量将有所帮助。 - Erol
我在想,是否可以在反序列化之前创建一个HashMap,并让readObject方法使用该特定的HashMap进行写入。你有什么想法吗? - Erol
尝试加载一个大的hashMap,这样你就可以从之前保留空间。HashMap<Foo> myMap = new HashMap<Foo>(numberOfElements * 2); 如果这样还不行,你可以尝试使用LinkedHashMap。如果我没记错的话,我也遇到了一些问题,而在Android中,LinkedHashMap反序列化更快(虽然没有任何意义,但我的时间是可靠的)。你也可以尝试一下。 - weakwire

3

你尝试过将HashMap序列化为JSON对象吗? Android对从文件反序列化JSON有很好的支持。


谢谢。这看起来像是标准序列化的不错替代品。如果我在使用 weakwire 的解决方案时失败的话,我会考虑使用它。 - Erol

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接