I'd go with List.of(array)
, as available from Java 9 on, which creates a copy of the source array internally and an immutable List from that. Note though, there there're no null
values allowed in this implementation.
If this is a requirement, Arrays.copyOf([T]source, int length)
can be used, if no real immutability is needed, but only the source array mustn't be modified.
Otherwise, if immutability of the target Collection is required, Java's immutable Collection
API or Guava might be your best shot e. g. Collections.immutableXX()
or ImmutableList.of()
.
If additional dependencies are not desired, one of the following approaches should work, depending on, whether further pre-processing is needed, before making the result immutable:
final T[] objects = (T[])new Object[] { null };
final T obj = (T)new Object();
final BinaryOperator<ArrayList<T>> listCombiner = (a,b) -> { a.addAll(b); return a; };
final Collector<T, ArrayList<T>, List<T>> collector = Collector.of(
ArrayList<T>::new, List::add, listCombiner, Collections::unmodifiableList
);
final List<T> list = Arrays.stream(objects).collect(collector);
or simply
final List<T> list = Collections.unmodifiableList(Arrays.asList(objects ));
Edit:
As already outlined, creating an immutable array in itself is not possible in Java.