Unmodifiable list in java can be created as:
List<String> unModifiableStringList = Collections.unmodifiableList(myActualModifiableList);
This is fine, but what is the actual runtime type of the list returned by the above function? How can we access that class? Is it even possible?
UPDATE: Actually I need to know at compile time that an unmodifiable list is being modified, Since I have to deal with a lot of lists, some of which are modifiable and others are not. So it is very cumbersome to keep track?
That is not possible.
Or at least, it is not possible without creating a completely different collections interface / class hierarchy. And that’s a bad idea because nothing designed to use regular collections would work with it.
I suppose it would be possible to write a static code analyser that could detect this kind of thing … in some cases … but that’s not strictly “compile time”. Besides, I’m not aware of any existing static code analyser that does this “out of the box”.
Well none of the ways you might do this really work.
Alternative #1:
While static typing can prevent us from using an unmodifiable list where a modifiable one is required, the reverse is not true. Every List is also an UnmodifiableList … and that doesn’t really make sense.
Alternative 2:
Now static typing can prevent us from using an modifiable list where an umodifiable one is required, but not the reverse. (That suits your requirement …) Furthermore, a class that implements
UnmodifiableListstill inherits theaddoperation, and there’s nothing to stop an application from trying to call it.In short, static type systems cannot adequately handle this kind of restriction.