Suppose I have a Map which is a private member variable of my class A.
In the same class I create an instance of class B, call it objB, by passing the map to B's constructor.
Obviously this is wrong, because I have leaked a private field to an object of a different class. That class might later on decide to modify the map passed to it, which would ruin everything.
Is it preferable to 1) pass is using Collections.unmodifiableMap or maybe 2) copying it? If there's another, better approach, I'd be glad to see it.
In case the map is modified in class A, objB should know the new map immediately. And this means I'd have to update the map in objB every time I modify it (but not if I pass it ad unmodifiable list).
I think option 2 is better, because in 1) we pass an unmodifiable collection to B, and B assumes the collections passed to it are modifiable.
class A {
Map<String, Integer> map;
public A() {
map = new HashMap<String, Integer>();
B objB = new B(map); //option 1
B objB = new B(Collections.unmodifiableMap(map)); //2
B objB = new B(new HashMap(map)); //3
}
}
class B{
Map<String, Integer> map;
public B(Map<String, Integer> map) {
this.map = map;
}
//use data from the map to do stuff
}