We cannot have List<int>
as int
is a primitive type so we can only have List<Integer>
.
Java 16
Java 16 introduces a new method on Stream API called toList()
. This handy method returns an unmodifiable List containing the stream elements. So, trying to add a new element to the list will simply lead to UnsupportedOperationException
.
int[] ints = new int[] {1,2,3,4,5};
Arrays.stream(ints).boxed().toList();
Java 8 (int array)
int[] ints = new int[] {1,2,3,4,5};
List<Integer> list11 =Arrays.stream(ints).boxed().collect(Collectors.toList());
Java 8 and below (Integer array)
Integer[] integers = new Integer[] {1,2,3,4,5};
List<Integer> list21 = Arrays.asList(integers); // returns a fixed-size list backed by the specified array.
List<Integer> list22 = new ArrayList<>(Arrays.asList(integers)); // good
List<Integer> list23 = Arrays.stream(integers).collect(Collectors.toList()); //Java 8 only
Need ArrayList and not List?
In case we want a specific implementation of List
e.g. ArrayList
then we can use toCollection
as:
ArrayList<Integer> list24 = Arrays.stream(integers)
.collect(Collectors.toCollection(ArrayList::new));
Why list21
cannot be structurally modified?
When we use Arrays.asList
the size of the returned list is fixed because the list returned is not java.util.ArrayList
, but a private static class defined inside java.util.Arrays
. So if we add or remove elements from the returned list, an UnsupportedOperationException
will be thrown. So we should go with list22
when we want to modify the list. If we have Java8 then we can also go with list23
.
To be clear list21
can be modified in sense that we can call list21.set(index,element)
but this list may not be structurally modified i.e. cannot add or remove elements from the list. You can also check this answer of mine for more explanation.
If we want an immutable list then we can wrap it as:
List<Integer> list22 = Collections.unmodifiableList(Arrays.asList(integers));
Another point to note is that the method Collections.unmodifiableList
returns an unmodifiable view of the specified list. An unmodifiable view collection is a collection that is unmodifiable and is also a view onto a backing collection. Note that changes to the backing collection might still be possible, and if they occur, they are visible through the unmodifiable view.
We can have a truly immutable list in Java 9 and 10.
Truly Immutable list
Java 9:
String[] objects = {"Apple", "Ball", "Cat"};
List<String> objectList = List.of(objects);
Java 10 (Truly Immutable list):
We can use List.of
introduced in Java 9. Also other ways:
List.copyOf(Arrays.asList(integers))
Arrays.stream(integers).collect(Collectors.toUnmodifiableList());
Arrays.asList(new int[] { 1, 2, 3 })
; definitely didn't compile in Java 1.4.2, because anint[]
is not aObject[]
.Arrays.asList
should work.