Home > Back-end >  Check if Java Collection is modifiable at Runtime
Check if Java Collection is modifiable at Runtime

Time:06-22

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.

CodePudding user response:

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.

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:

  • You can't just test for the (private) UnmodifiableCollection etc classes. Other collection classes can be unmodifiable.

  • Even within the Java SE class library, the classes you would need to test for actually differs between different Java versions. (See @Holger's comment!)

  • You can't use instanceof because someone could subclass a modifiable class to be unmodifiable ... or vice versa.

  • Modifiability could depend on a collection object's runtime state. For example, the object could have a "frozen" flag that can be set after populating the collection using add methods.

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.

CodePudding user response:

try below:

if(yourcolletion.getClass().getSimpleName().equals("UnmodifiableCollection")) {
 //can not modified
} else {
//given list is modifiable
}

you can also add for more check for UnmodifiableList etc.

Note: I would have recommended to use instanceof instead of checking for class name but you can not import the UnmodifiableList or UnmodifiableCollection classes into your code

  • Related