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.
Nice article . There is good coding example collection visit
ReplyDeleteTop coding program example