Reputation: 3922
I have ConcurrentMap<Integer, MyObj>
in my program.
Can I modify MyObj
if I know a key? Without deleting and putting a new MyObj
?
Upvotes: 0
Views: 134
Reputation: 3377
Not only that, but if you keep the original reference to the object, you can still modify it.
MyObject o = new MyObject();
myMap.put("key", o);
o.setName("foo");
myMap.get("key").getName(); //will return "foo"
myMap.get("key").setName("bar");
myMap.get("key").getName(); //will return "bar"
o = null; //this applies only for your local reference, not for the map
myMap.get("key").getName(); //will STILL return "bar"
Upvotes: 3
Reputation: 647
Yes you can. The map simply holds a reference to the object. The object can change without having to update the map.
Map<Integer, MyObj> myMap = new ConcurrentMap<Integer, MyObj>();
myMap.put(1, new MyObj());
MyObj obj = myMap.get(1);
obj.setFoo("Foo");
Upvotes: 0
Reputation: 359816
It depends on your definition of "modify." If you want to mutate something internal to MyObj
, and that object is mutable, you certainly can do this.
ConcurrentMap<Integer, MyObj> map = /* snip */;
map.get(someKey).callMutatorMethod();
If you want to replace the object with an entirely new instance, you can just call Map#put()
, which will overwrite the existing mapped value, if such a value exists.
Upvotes: 4