0

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.

user1974753
  • 1,359
  • 1
  • 18
  • 32
  • 2
    `ImmutableMultimap#get` returns an `ImmutableCollection`. There's no need to copy it. If you need a `List` however... – Savior Apr 14 '16 at 17:21
  • In the Google Guava docs( http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/ImmutableListMultimap.html) it states mmutableMultimap#get returns an ImmutableList... – user1974753 Apr 14 '16 at 17:23
  • 3
    Also, `ImmutableList.copyOf` will not actually copy an `ImmutableList` anyway. – Paul Boddington Apr 14 '16 at 17:24
  • @user1974753 You're looking at `ImmutableListMultimap`, but your code has `ImmutableMultimap`. In any case, they're both immutable. – Savior Apr 14 '16 at 17:29

1 Answers1

5

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
ColinD
  • 108,630
  • 30
  • 201
  • 202