我有以下HashMap:
HashMap<String,Object> fileObj = new HashMap<String,Object>();
ArrayList<String> cols = new ArrayList<String>();
cols.add("a");
cols.add("b");
cols.add("c");
fileObj.put("mylist",cols);
我将其写入文件,如下所示:
File file = new File("temp");
FileOutputStream f = new FileOutputStream(file);
ObjectOutputStream s = new ObjectOutputStream(f);
s.writeObject(fileObj);
s.flush();
现在我想把这个文件读回一个HashMap,其中Object是一个ArrayList,如果我简单地这样做:
File file = new File("temp");
FileInputStream f = new FileInputStream(file);
ObjectInputStream s = new ObjectInputStream(f);
fileObj = (HashMap<String,Object>)s.readObject();
s.close();
这不会以我保存它的格式给出对象。它返回一个包含15个空元素和第3个元素的〈mylist,[a,b,c]〉对的表。我希望它只返回一个包含我最初提供给它的值的元素。
//如何将相同的对象读回HashMap?
好吧根据杰姆的笔记这似乎是正确的解释:
- ObjectOutputStream以ObjectInputStream能够理解的反序列化格式序列化对象(在本例中为HashMap),并对任何可序列化的对象通用地执行此操作。如果希望它以所需的格式序列化,则应编写自己的序列化程序/反序列化程序。**
- 就我而言:当我从文件中读回Object时,我只是在HashMap中迭代这些元素中的每一个,并获取数据,然后对它做任何我想做的事情(它只在有数据的地方进入循环)。
谢谢你,
6条答案
按热度按时间vwkv1x7d1#
你似乎混淆了HashMap的内部表示和HashMap的行为。集合是相同的。下面是一个简单的测试来证明这一点。
cs7cruho2#
我相信你正在犯一个常见的错误。你在使用后忘记关闭流!
wooyq4lh3#
也可以使用JSON文件读写MAP对象。
将Map对象写入JSON文件
从JSON文件读取Map对象
并从Jackson导入ObjectMapper,然后将代码放入try catch块中
mefy6pfw4#
您的第一行:
让我犹豫了一下,因为值不能保证是
Serializable
,因此可能不能正确地写出来。你应该真正地将对象定义为HashMap<String, Serializable>
(或者如果你愿意,简单的Map<String, Serializable>
)。我还将考虑以简单的文本格式(如JSON)序列化Map,因为您正在进行简单的
String -> List<String>
Map。tkqqtvp15#
我相信您已经得到了所保存的内容。在保存之前检查过Map了吗?在
HashMap
中:例如,默认的
HashMap
将从16null
开始。您使用了其中一个存储桶,因此在保存时只剩下15null
,这是您加载时得到的结果。请尝试检查fileObj.keySet()
、.entrySet()
或.values()
以查看您所期望的结果。HashMap
的设计目的是在内存不足的情况下提高速度。有关详细信息,请参阅Wikipedia's Hash table条目。z9zf31ra6#
相同的数据(如果要写入文本文件)