Question

The java.util.Collections class allows me to make collection instances unmodifiable. The following method

protected Map<String, List<String>> getCacheData() {
    return Collections.unmodifiableMap(tableColumnCache);
}

returns an umodifiable Map, so that an UnsupportedOperationException is caused by attempting to alter the map instance.

@Test(expected = UnsupportedOperationException.class)
public void checkGetCacheData_Unmodifiable() {
    Map<String, List<String>> cacheData = cache.getCacheData();
    cacheData.remove("SomeItem");
}

Unfortunately all List<String> childs aren't unmodifiable. So I want to know whether there is a way to enforce the unmofiable behavior for the child values List<String> too?

Of course, alternatively I can iterate through the maps key value pairs, make the lists unmodifiable and reassemble the map.

Was it helpful?

Solution

You need an ImmutableMap full of ImmutableList instances. Use Guava to preserve your sanity.

To start off, create ImmutableList instances that you require:

ImmutableList<String> list1 = ImmutableList.of(string1, string2, etc);
ImmutableList<String> list2 = ImmutableList.of(string1, string2, etc);

Then create your ImmutableMap:

ImmutableMap<String,List<String>> map = ImmutableMap.of("list1", list1, "list2", list2);

There are numerous ways to instantiate your immutable lists and maps, including builder patterns. Check out the JavaDocs for ImmutableList and ImmutableMap for more details.

OTHER TIPS

Unfortunately you will need to wrap each List as an unmodifiable List. This can be done by using java.util.Collections.unmodifiableList(...). If you have control over the creation of the Lists, then you can (and should) do this immediately after you set your values. If you don't have control over the creation of these collections, then you may want to rethink making it unmodifiable because some other code you are unaware of may be relying on that behavior. Hope that helps.

Maybe that's not exactly what you need but I recommend to use Guava immutable list multimap

Subclass Map to return unmodifiable lists.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top