duracell
duracell

Reputation: 724

java clone deep copy HashMap

In my webapplication, I've to bring the same data from DB into the webapplicatio, which takes lots of time. What I did is, that I took the data and put it into the HashMap. That way I dont't have to bring it every time into the webapplication. But the big problem is, that all user will operate on the same data, which they change. My first question is: Is it correct, to save the data brought from DB in a HashMap, so I don't have to query it from DB every time? My second question is, in case I can use a HashMap to save the data, I've to make a deep copy or clone of the data brought and put in the HashMap, so each user have a copy of the origin data. right?

The Object I've to clone is, a transfer object, which has references to other Object and HashMaps. The process is so: bring first the data from DB, make classes and put all classes into a transfer object and put that transfer object into a hashmap. next time, bring the data from hashmap.

Thanks for every help. Edit: That data coming from DB creates a online form and has default values like name and address and sex... All user have to edit the form for their own purposes. Thats way every user must have his own copy to operate on it.

Upvotes: 1

Views: 7194

Answers (1)

lance-java
lance-java

Reputation: 27994

A very simple way to deep clone is to serialize / deserialize the object. This will ONLY work if all keys / values in your hashmap implement java.io.Serializable.

eg:

public <T extends Serializable> T deepClone(T o) {
    ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
    ObjectOutputStream out = new ObjectOutputStream(byteOut);
    out.writeObject(o);
    out.flush();
    ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(byteOut.toByteArray());
    return o.getClass().cast(in.readObject());
}

Upvotes: 4

Related Questions