简体   繁体   English

java克隆深拷贝HashMap

[英]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. 在我的Web应用程序中,我必须将相同的数据从DB引入到webapplicatio中,这需要很多时间。 What I did is, that I took the data and put it into the HashMap. 我所做的是,我获取了数据并将其放入HashMap中。 That way I dont't have to bring it every time into the webapplication. 这样,我不必每次都将其带入Web应用程序。 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? 我的第一个问题是:将来自数据库的数据保存到HashMap中是否正确,所以我不必每次都从数据库查询数据? 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. 我的第二个问题是,如果可以使用HashMap保存数据,则必须对引入和放入HashMap的数据进行深层复制或克隆,以便每个用户都有原始数据的副本。 right? 对?

The Object I've to clone is, a transfer object, which has references to other Object and HashMaps. 我要克隆的对象是一个传输对象,它具有对其他Object和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. 流程是这样的:首先从DB中获取数据,创建类,然后将所有类放入传输对象,然后将该传输对象放入哈希映射。 next time, bring the data from hashmap. 下次,从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. 编辑:来自DB的数据将创建一个在线表单,并具有默认值,例如名称,地址和性别...所有用户都必须出于自己的目的编辑表单。 Thats way every user must have his own copy to operate on it. 这样,每个用户都必须拥有自己的副本才能对其进行操作。

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 . 仅当哈希图中的所有键/值都实现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());
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM