javacollectionsunmodifiable

Check if Java Collection is modifiable at Runtime


I'm trying to make a method that modifies a incoming Collection or List. The problem is that I can't check if the Collection / List is an unmodifiable Collection / List. Sure I could just "try" to write to it with set and catch the exception. But I think we agreed that try catch is not a valid control flow tool. Is there something I'm missing? Any method that returns a boolean (modifiable or not) or an interface that signals modifiablity / unmodifiablity? I think there should be since the collection api is single typed (doesn't distinguish between modifiable and not by the type passed around). But when you want to write to a collection you get passed you can't be sure it's modifiable.


Solution

  • But I think we agreed that try catch is not a valid control flow tool.

    It is debatable. But lets not debate it.

    Is there something I'm missing?

    No.

    [Is there] any method that returns a boolean (modifiable or not) or an interface that signals modifiablity / unmodifiablity?

    No and No.

    There is no standard API method or marker interface. (I guess you could implement your own ... but you would run into difficulties when using the standard collection implementation classes.)

    The best you could do is to do some messy tests for specific implementation classes that are known to be modifiable or non-modifiable. But that approach has problems too:

    In general, catching the exception is the most practical solution, irrespective of your feelings on how "proper" it is to use exceptions for this.


    If course ... if you have total control over the collection classes that are used in your application, or may be encountered by your library ... then testing the classes may be more viable.