Question:
It is known that there is a java.util.Collections
class that has methods of the unmodifiable*
type that return immutable collections. Now the question is how to determine that a collection is immutable?
Answer:
You will hardly find any universal good solution.
In my opinion, the least crutch is .getClass().isInstance(...)
:
List<String> list = new ArrayList<>();
List<String> unmodifiableList = Collections.unmodifiableList(list);
boolean isUnmodifiable = Collections.unmodifiableList(list).getClass().isInstance(unmodifiableList);
More options:
- Catch
UnsupportedOperationException
when adding an element. But then, in the case of a mutable collection, the element must be removed after the test. -
.getClass().getSimpleName().equals(...)
.