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

I just noticed that ImmutableList.of(E[]) deprecated in favor of ImmutableList.copyOf() , for the obvious reason that the list cannot really be made immutable if the original array is used elsewhere.

What if you have a method that returns an array, and you know that the method does not contain an array reference, and your code does not hold an array reference other than passing to ImmutableList.of() ?

Should I...

  • keep using ImmutableList.of(E[]) (this 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 in which performance / resource problems do not arise, otherwise a copy is not needed.
+8
java collections guava
source share
1 answer

ImmutableList.of(E[]) does not store and never stores the array specified by it (this would not be immutable if it happened to defeat a class point). It was deprecated to explain the reasons. If you look at the implementation, this is:

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

So my advice would be to simply use ImmutableList.copyOf() as a whole. If you know that you are just wrapping the array for internal use or some of them, feel free to save a copy and just use Arrays.asList , but I would prefer ImmutableList for the API.

+16
source share

All Articles