Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.
like image 443
Jason S Avatar asked Jul 21 '11 14:07

Jason S


1 Answers

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.

like image 106
ColinD Avatar answered Nov 07 '22 15:11

ColinD