fishtoprecords
fishtoprecords

Reputation: 2404

Best practice: how do I tell if a collection/set/let is a Guava ImmutableSet/Immutable map?

I've got a bug in my code, I'm trying to modify a List that is really a Guava ImmutableList passed in from a client program/programmer.

What is the best way to test for this, rather than waiting for the exception when the .add() fails?

Upvotes: 3

Views: 2775

Answers (4)

Louis Wasserman
Louis Wasserman

Reputation: 198123

What is the best way to test for this, rather than waiting for the exception when the .add() fails?

If you don't know if the returned list is mutable, you should copy it to a mutable collection anyway. If the returned list is another ArrayList, the cost of the copy is minimal -- it reduces to a blazing fast System.arraycopy.

(That said, for the client library to sometimes return modifiable lists and sometimes unmodifiable lists is itself an act of evil.)

If you must check at runtime, use instanceof ImmutableMap or ImmutableCollection or whatever's appropriate.

Upvotes: 10

卢声远 Shengyuan Lu
卢声远 Shengyuan Lu

Reputation: 32004

'instanceof' is definitely okay.

But if possible I would recommend use ImmutableList in method signature instead of List. Because ImmutableList is-a List in syntax, but actually ImmutableList throws UnsupportedOperationException when addXXX(), removeXXX(), clear() is called.

Upvotes: 0

Francisco Spaeth
Francisco Spaeth

Reputation: 23903

For specific Guava, you could check if the instance is a com.google.common.collect.ImmutableCollection.

if (list instanceof com.google.common.collect.ImmutableCollection) {
   // is immutable
}

For immutable map you need to check if instance is a com.google.common.collect.ImmutableMap

Upvotes: 4

Martin Matula
Martin Matula

Reputation: 7989

Checking if the list is one of the ImmutableCollection subtypes is easy:

if (list instanceof ImmutableCollection) {
    // do whatever you want to do if the list is a Guava immutable collection/set/list/multiset
}

However that does not give you a generic solution of figuring out if the list is immutable or not (there may be user-implemented lists that are immutable or the unmodifiable list obtained from Collections.unmodifiableList()).

So if you want a generic solution, you still have to catch exceptions list.add() method may throw.

Upvotes: 2

Related Questions