Is their some existing mechanism using which I can enforce that a collection is modifiable only in specific class(es) and is read-only elsewhere?I had a look a unmodifiable collection but they are unmodifiable everywhere.
If the creation of the collection is out of the hands of the class in which it is to be modifiable, then it is impossible to make it modifiable inside that class.
Suppose that someone passes you an immutable list (of an interface type). You don't know what implementation is behind the interface. It could be an implementation that doesn't have any methods to mutate it at all. You can't magically create those methods when you need them.
Why do you have this requirement? If the program has been properly designed, there's probably a good reason why the collection that you get passed is immutable, and you should find a different solution for the problem you're facing.
What else is the class responsible for with respect to the collection? At this moment, it sounds like the collection should be created in the constructor of the class protecting it from being modified.
Joined: Jan 01, 2007
Thanks for replying!!
Let me add the exact details. Maybe there is a problem with the design itself.
Basically I have a class called graph which gets a set of vertices and a set of edges in the constructor. There are getters for these sets as well in the class. Now I want to avoid any additions/deletions to these sets outside the graph class except the explicit call to graph.addVertex or graph.addEdge. This is necessary to avoid any graph manipulations without the graph class knowing about it.