I recently found out that there are actually 2 different ArrayList
implementations in Java (better late than never I guess...).
So I was wondering why does Arrays.asList(T... a)
need to return a list which can not be resized ? If they needed an unmodifiable list why add the set(int index, E element)
method then ?
So my general question is why not return the java.util.ArrayList
from the Arrays.asList(T... a)
method ?
Also what do you gain with the java.util.Arrays.ArrayList
implementation ?
asList method returns a type of ArrayList that is different from java. util. ArrayList. The main difference is that the returned ArrayList only wraps an existing array — it doesn't implement the add and remove methods.
asList returns a fixed-size list that is backed by the specified array; the returned list is serializable and allows random access.
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.
We can use Arrays#asList method to create a List instance from an Array. Before we move ahead, the next snippet shows how to create a list from array using asList method. However, the asList method does not convert array, neither it copies elements.
You asked:
Also what do you gain with the java.util.Arrays.ArrayList implementation ?
It is because the Arrays$ArrayList returned by Arrays.asList is just a view on the original array. So when the original array is changed then the view is changed too.
If one would use an real ArrayList then the elements will be copied, and a change on the orignal array would not infuence the ArrayList.
The reasons to do this are quite simple:
The javadoc says that asList
returns "a fixed-size list backed by the specified array". If you want to resize the array, you have to create a new one and copy the old data. Than the list won't be backed by the same array instance. The stated goal is "This method acts as bridge between array-based and collection-based APIs." and so write-through to the underlying array is a design requirement.
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