Wickoo
Wickoo

Reputation: 7345

Guava copyOf nested collections

Let's say I have the following Map definition:

Map<String, List<Set<Integer>>> map = Maps.newHashMap();
map.put("a", Arrays.asList(Sets.newHashSet(1, 2, 3), Sets.newHashSet(4, 5)));

I create an immutable copy of the map as follows:

ImmutableMap<String, List<Set<Integer>>> immutableMap = ImmutableMap.copyOf(map);

If I call immutableMap.get("a").add(Sets.newHashSet(4));I get an error indicating that the nested List is also immutable in the copied collection. However, if the call to immutableMap.get("a").get(1).add(6); can be executed and if I printout the result I will get:

{a=[[1, 2, 3], [4, 5, 6]]}

Does it mean that copyOf only makes nested immutable collections one-level deep?

Upvotes: 0

Views: 1143

Answers (1)

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 279960

No, that's because Arrays#asList(Object...) returns an fixed-size List, ie. from which you cannot add or remove elements.

The ImmutableMap#copyOf(..) javadoc states

Returns an immutable map containing the same entries as map.

So the value of the entry with key "a" is the List returned by Arrays#asList(Object...).

Upvotes: 4

Related Questions