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...
ImmutableList.of(E[])
(seems like a bad idea since the method will go away)Collections.unmodifiableList(Arrays.asList())
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With