Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make a Map<String, List<String> unmodifiable? [duplicate]

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.

like image 213
My-Name-Is Avatar asked Sep 30 '13 13:09

My-Name-Is


People also ask

Is Unmodifiable list immutable?

If you create a List and pass it to the Collections. unmodifiableList method, then you get an unmodifiable view. The underlying list is still modifiable, and modifications to it are visible through the List that is returned, so it is not actually immutable.

What is Unmodifiable list in Java?

The unmodifiableList() method of java. util. Collections class is used to return an unmodifiable view of the specified list. This method allows modules to provide users with “read-only” access to internal lists.


2 Answers

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.

like image 162
Jason Nichols Avatar answered Sep 20 '22 11:09

Jason Nichols


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.

like image 26
babernathy Avatar answered Sep 21 '22 11:09

babernathy