Search code examples
javaguavaimmutabilitydefensive-copy

Passing an immutable list to ImmutableList.copyOf()?


I have the following code:

private static final ImmutableMultimap<String, String> namesToAddress;

public static List<String> getAddresses(String name){
  return ImmutableList.copyOf(namesToAddress.get(name));
}

My question is wheter the defensive copyOf() here is necessary, as the get() returns an immutable list anyway?

Note I am using ImmutableMultiimap from Google Guava.

Thanks.


Solution

  • Couple things (mostly covered in the comments, but as an answer):

    • If you use ImmutableListMultimap as the type for namesToAddresses, get() will return an ImmutableList; no need to call copyOf or cast or anything
    • Even if you don't do that, ImmutableMultimap.get() will return an ImmutableCollection; ImmutableCollections have an asList() method to view (or copy if necessary) the collection as an ImmutableList
    • Calling ImmutableList.copyOf(ImmutableCollection) will end up calling asList() on the collection anyway