We have known, value of element will be clone when we get it from a Map, such as:
Map<String, MyObject> map = new HashMap();
MyObject obj = new MyObject();
//put
map.put("id1", obj);
//get
MyObject obj1 = map.get("id1");
MyObject obj2 = map.get("id1"); //"obj2" is only a clone of "obj1"
//change some things
obj1.setName("AAA");
obj2.setName("BBB");
//show: they are different
obj1.printName(); //Print: AAA
obj2.printName(); //Print: BBB
But, i want a Map that return original instance, is there kind of Map like that?
Map<String, MyObject> map = new AUnknownMap();
MyObject obj = new MyObject();
//put
map.put("id1", obj);
//get
MyObject obj1 = map.get("id1");
MyObject obj2 = map.get("id1"); //"obj2" and "obj1" refer the same instance
//change some things
obj1.setName("AAA");
obj2.setName("BBB");
//show: they are the same
obj1.printName(); //Print: BBB
obj2.printName(); //Print: BBB
We have known, value of element will be clone when we get it from a Map
No, it won't. It's unclear exactly how you're seeing your original output, but that's not the normal behaviour.
Here's a short but complete example based on your code:
import java.util.HashMap;
import java.util.Map;
class MyObject {
private String name;
public void setName(String name) {
this.name = name;
}
public void printName() {
System.out.println(name);
}
}
class Test {
public static void main(String[] args) throws Exception {
Map<String, MyObject> map = new HashMap<>();
MyObject obj1 = new MyObject();
map.put("id1", obj1);
MyObject obj2 = map.get("id1");
obj1.setName("AAA");
obj2.setName("BBB");
obj1.printName();
obj2.printName();
}
}
This prints "BBB" twice, contrary to the claim in the question.
Presumably you've got code a bit like your sample code, which produces the different output that we can't reproduce with the code you have provided. You should examine your real code closely to work out where the difference is between that and what you've provided. No cloning occurs by default with any of the standard collections.
See more on this question at Stackoverflow