Reputation: 8896
I know of at least 2 mechanisms to enforce that a Collection should not be modified:
However, I notice both of them enforce the contract at runtime, by throwing exceptions (e.g UnsupportedOperationException).
Questions:
Upvotes: 4
Views: 486
Reputation: 3854
The original authors of the Collections APIs (unfortunately) did not make a distinction between immutable and mutable collections. An immutable API would have no mutating methods (but would likely rebuild collections internally as Persistent data structure).
See Scala as an example of a Collections API on the JVM that supports both immutable and mutable collections.
Upvotes: 2
Reputation: 272647
You could only do this by having no mutating methods on the class. But you're stuck if you want to implement an existing interface that has methods with mutating semantics (even static analysis won't help you in the general case).
Upvotes: 2