java - How to get a copy of object from hashmap without modifying its value in the Hashmap -


i using concurrenthashmap stores objects. want object , modify without modifying hashmap. how do it? following code:

concurrenthashmap<string,employee> datastorage = new  concurrenthashmap<string,employee>(10000); datastorage.put("employee1", employee1); 

i had added object of type employee hashmap. when

employee employee1 = datastorage.get("employee1"); 

if modify employee1, updated object gets stored in hashmap

how modify employee1 without affecting value stored in hashmap?

you can make deep copy of object employee i.e. create new object rather passing memory location of employee object.

to learn more deep copy read here.

you can using this:

/**    * method makes "deep clone" of object given.    */   public static object deepclone(object object) {     try {       bytearrayoutputstream baos = new bytearrayoutputstream();       objectoutputstream oos = new objectoutputstream(baos);       oos.writeobject(object);       bytearrayinputstream bais = new bytearrayinputstream(baos.tobytearray());       objectinputstream ois = new objectinputstream(bais);       return ois.readobject();     }     catch (exception e) {       e.printstacktrace();       return null;     }   } } 

for more can read here.

also can use clone() implementing cloneable.

read here clone() or here.


Comments

Post a Comment

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -