if we retrieve value fro开发者_如何学Pythonm Map and then we do some changes , so we again need to put that object back on Map
for ex
Human human = (Human ) domainObjects
.get(Constants.Human;
human.setName("Vish");
domainObjects.put(Constants.Human, human);
Or as we are passing the reference of object,the changes will be also present in the domain object even without using Map put function
Map returns a copy of a reference to the underlying object. Not a copy of the object. When you call setName you are changing the object.
It would appear you should be using enums for you Constants or plain classes.
Map<EnumType, Object> map = new EnumMap<EnumType, Object>(EnumType.class);
Human human = (Human) map.get(EnumType.Human);
or
Map<Class, Object> map = new LinkedHashMap<Class, Object>();
Human human = (Human) map.get(Human.class); // no need for a constant.
No need to put it again. changes will be on the single object.
- If you get an Object from the HashMap, it is passed to you as a reference and thus any call to its methods will affect the object contained in the Map.
- Note however that a new instanciation will not affect the Object contained in the Map.
Example:
Map<Integer, Human> map = new HashMap<Integer, Human>();
map.put(1, new Human("Toto"));
Human human = map.get(1);
human.setName("Tutu");
human = new Human("Tata");
System.out.println(map.get(1).getName()); // "Tutu"
System.out.println(human.getName()); // "Tata"
Java works with reference to Objects, not with primitives thou. So you will be working with the same "memory chunk" all of the time. Changes are visible in all variable that points to that object.
NO. you need understand two concepts, variable and object, and know java is passing object by reference.
'human' that you write down and declared in you .java source file is a variable , in run time, 'human' variable is a reference to some object.
so any method return value is actually a variable that refer to a object. (basically, most time, in simple case ...)
when you call variable.method(), it actually tell jvm to invoke the referenced object's method.
in you case, it is update the object (that refer by 'human' variable ) 'Name' field with value 'wish'
精彩评论