How to make objects of the same class have independent containers.Map member?

3 views (last 30 days)
I create my own class as below:
classdef testClass < handle
properties
value;
map = containers.Map('KeyType','double','ValueType','any');
end
end
My goal is for each object of testClass to maintain its own map. However, it turns out that there is only one map object that for the whole class: all objects of testClass access to the same containers.Map. For example, if I create two objects as follows
a = testClass;
b = testClass;
a.value = 'a';
b.value = 'b';
a.map(1) = 123;
b.map(2) = 321;
It ends up both a and b's map contains two key-value pairs:
>> a
a =
testClass handle
Properties:
value: 'a'
map: [2x1 containers.Map]
>> b
b =
testClass handle
Properties:
value: 'b'
map: [2x1 containers.Map]
Methods, Events, Superclasses
Both (key,value) pairs (1,123) and (2,321) appears in both a.map and b.map
>> a.map.keys
ans =
[1] [2]
>> a.map.values
ans =
[123] [321]
>> b.map.keys
ans =
[1] [2]
>> b.map.values
ans =
[123] [321]
Is this a bug? How can I keep independent containers.Map for each class object??

Accepted Answer

Peter Perkins
Peter Perkins on 3 Oct 2013
Guanfeng, the problem is that you're initializing the map property in the properties block, and the value you're initializing with is a handle. Your class creates the value on the right hand side of
map = containers.Map('KeyType','double','ValueType','any');
once, and assigns it to that property in each new instance. But because that value is a handle, the assignment just copies the handle, and so all the properties point to the same map. This would not happen if you initialized with a value that wasn't a handle.
The solution is to put the initialization of that property into the testClass constructor.
Hope this helps.

More Answers (0)

Categories

Find more on Class File Organization in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!