开发者

guava: best practices with ImmutableList.of(E[])

I just noticed that ImmutableList.of(E[]) is deprecated in favor of ImmutableList.copyOf(), for the obvious reason that the list can't truly be made immutable if the raw array is used elsewhere.

What if you have a method that returns an array, and you know for a fact that the method doesn't hold onto 开发者_如何转开发a reference to the array, and your code doesn't hold onto a reference to the array other than passing it to ImmutableList.of()?

Should I...

  • continue to use ImmutableList.of(E[]) (seems like a bad idea since the method will go away)
  • use Collections.unmodifiableList(Arrays.asList())
  • use ImmutableList.copyOf() -- this seems like the best idea where performance/resource issues don't arise, otherwise the copy is unnecessary.


ImmutableList.of(E[]) does not and has never stored the array it's given directly (it wouldn't be immutable if it did, which would defeat the point of the class). It was deprecated for naming reasons. If you take a look at the implementation, it is:

public static <E> ImmutableList<E> of(E[] elements) {
  return copyOf(elements);
}

So my advice would be to just use ImmutableList.copyOf() in general. If you know you're just wrapping an array for internal use or some such, feel free to save yourself the copy and just use Arrays.asList but I'd prefer ImmutableList for the API.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜