将不可变列表传递给 ImmutableList.copyOf()?

Passing an immutable list to ImmutableList.copyOf()?

我有以下代码:

private static final ImmutableMultimap<String, String> namesToAddress;

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

我的问题是这里的防御性 copyOf() 是否有必要,因为 get() returns 无论如何都是一个不可变的列表?

注意我使用的是 Google Guava 的 ImmutableMultiimap。

谢谢。

一些事情(大部分都包含在评论中,但作为一个答案):

  • 如果您使用 ImmutableListMultimap 作为 namesToAddresses 的类型,get() 将 return 和 ImmutableList;无需调用 copyOf 或 cast 或任何东西
  • 即使您不这样做,ImmutableMultimap.get() 也会 return 一个 ImmutableCollectionImmutableCollections 有一个 asList() 方法来查看(或在必要时复制)集合作为 ImmutableList
  • 调用 ImmutableList.copyOf(ImmutableCollection) 最终会在集合上调用 asList()