When we create a list from an array using java.util.Arrays.asList()
, the list is immutable. I am just curious to know why do we want to create a immutable list when the basic purpose of List
(or Set
or Map
) is to have dynamic size and to be able to add, remove elements at will. When we need a fixed size data structure we go for Array and when we need a dynamic data structure we go for List
or Set
or Map
etc. So what is the purpose of having a immutable list? I came across this while working on my assignment.
Arrays. asList() , the list is immutable.
The asList() method of java. util. Arrays class is used to return a fixed-size list backed by the specified array. This method acts as a bridge between array-based and collection-based APIs, in combination with Collection.
asList returns a fixed-size list that is backed by the specified array; the returned list is serializable and allows random access.
When we create a list from an array using java.util.Arrays.asList() , the list is mutable.
Yes and no: The list may be modified, by calling
list.set(index, element);
But the list may not be structurally modified. That means that it is not possible to add elements to the list or remove elements from the list. The reason simply is that the list is still backed by the array, and the size of the array may not change.
When we need a fixed size mutable collection we go for Array
And that's the key point here: An array is not a Collection. The Arrays.asList
method mainly serves as a "bridge" between the "arrays world" and the "collections world".
The Arrays.asList
method allows you, for example, the pass data to a method that expects a Collection
:
// A method that expects a collection: void process(List<String> strings) { ... } void call() { String array[] = new String[] { "A", "B", "C" }; // Pass the array (as a list) to the method: process(Arrays.asList(array)); }
This application case includes creating other collections from an array. For example, if you have an array and want to create a Set
containing the elements from the array, you could to
String array[] = new String[] { "A", "B", "C" }; Set<String> set = new HashSet<String>(); for (String s : array) { set.add(s); }
But with the Arrays.asList
method, this can be done more conveniently:
Set<String> set = new HashSet<String>(Arrays.asList(array));
The Arrays.asList
method is so to say the counterpart of the Collection#toArray method, which works in the opposite direction (although this method usually involves creating and filling a new array, whereas the Arrays.asList
method just "wraps" an array and lets it "look like" a List
).
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