user1621988
user1621988

Reputation: 4335

How to save and load a HashMap<String,Object>?

HashMap

public Map<String, BarrackData> barrack = new HashMap<String, BarrackData>();

BarrackData.java

public class BarrackData {
int A;
int B;
int C;
int D;
int E;
String Title;

public BarrackData(int a, int b, int c, int d, int e, String title) {
    A = a;
    B = b;
    C = c;
    D = d;
    P = p;
    Title = title;
}

How can I save this HashMap? And load it?
I tried different methodes with Objectin/outputstream,
it ended up with NotSerializable, ObjectSteam and IO exception,
Where i have no clue how to deal with them.

Upvotes: 2

Views: 3646

Answers (3)

weberc2
weberc2

Reputation: 7908

You must make your Object class serializable (give it serialize() and deserialize() methods which convert it to/from a string or some such that can be saved/loaded). Apparently, HashMaps facilitate some level of serialization out of the box.

Here is a link to a tutorial on Java serialization: http://www.tutorialspoint.com/java/java_serialization.htm

and here is some more detailed info on HashMap serialization: Serializing and deserializing a map with key as string

As Bohemian mentioned, implementing Serializable is the standard way to do this.

Upvotes: 0

Mik378
Mik378

Reputation: 22171

To complete answers, pay attention to the fact that the outcome of keySet() belonging to HashMap (if you need it at any time) is not Serializable.

Indeed, keys aren't supposed to be dissociated from values concerning an HashMap.

Upvotes: 0

Bohemian
Bohemian

Reputation: 424993

Only Serializable classes may be serialized: Just add implements Serializable to your class:

public class BarrackData implements Serializable {


Note that to actually be serialized, all fields within the class must be Serializable, however java primitives, arrays (if the element type is Serializable), java.lang classes (like String) and Collections (if the element type is Serializable) are Serializable, so you're OK.

Upvotes: 2

Related Questions