Skip to main content

Serializing HashMap

2 replies [Last post]
dinaharchery
Offline
Joined: 2007-08-13

Hello all,

I am a newbie to java and am looking for a quick answer which I am sure that you experts out there can answer easily.

I have a HashMap that I would like to serialize seperately from another group of ArrayLists. The reason is long and drawn-out - suffice to say that my boss wants this given structure.

I am able to read-in ths set of Objects from the ArrayList with the following code:
ObjectInputStream in = new ObjectInputStream(new FileInputStream(binFile));
ArrayList data = new ArrayList();
data = (ArrayList)in.readObject();
in.close();

But suppose I would like to place my HashMap at the beginning of the serialized Object, is there a simple way to read-in the objects of the HashMap prior to the arrayList. Maybe something like:
ObjectInputStream in = new ObjectInputStream(new FileInputStream(binFile));
HashMap mapDat = new HashMap();
mapDat = (HashMap)in.readObject(0, sizeOfHashMap);
ArrayList data = new ArrayList();
data = (ArrayList)in.readObject();
in.close();

I sure there is a simple solution but I am pretty new to Java and sure could use some help. If anyone is feeling kind to a java newbie, please help.

Thanks.

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
tarbo
Offline
Joined: 2006-12-18

Objects are read in the order they were written. Multiple objects can be serialised to the same stream. If you serialise as follows:
[code]
ObjectOutputStream out = // ...
out.writeObject(mapDat);
out.writeObject(data);
[/code]
...you can simply read in the same order:
[code]
ObjectInputStream in = // ...
HashMap mapDat = (HashMap) in.readObject();
ArrayList data = (ArrayList) in.readObject();
[/code]

There is no need to construct new objects prior to deserialising: an equivalent object is recreated.
[code]ArrayList data = new ArrayList();
data = (ArrayList)in.readObject();[/code]
...should really just be...
[code]ArrayList data = (ArrayList)in.readObject();[/code]

I hope that's what you wanted to know.

dinaharchery
Offline
Joined: 2007-08-13

Thank you, tarbo. This is exactly what I was looking for.