How to read and write a HashMap to a file?

前端 未结 5 438
南笙
南笙 2020-12-09 04:13

I have the following HashMap:

HashMap fileObj = new HashMap();

ArrayList cols         


        
5条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-09 04:36

    You appear to be confusing the internal resprentation of a HashMap with how the HashMap behaves. The collections are the same. Here is a simple test to prove it to you.

    public static void main(String... args)
                                throws IOException, ClassNotFoundException {
        HashMap fileObj = new HashMap();
    
        ArrayList cols = new ArrayList();
        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.close();
        }
        File file = new File("temp");
        FileInputStream f = new FileInputStream(file);
        ObjectInputStream s = new ObjectInputStream(f);
        HashMap fileObj2 = (HashMap) s.readObject();
        s.close();
    
        Assert.assertEquals(fileObj.hashCode(), fileObj2.hashCode());
        Assert.assertEquals(fileObj.toString(), fileObj2.toString());
        Assert.assertTrue(fileObj.equals(fileObj2));
    }
    

提交回复
热议问题