I read this post: Difference between Arrays.asList(array) vs new ArrayList<Integer>(Arrays.asList(ia)) in java
and I have a question about it. I look at the line:
List<Integer> list2 = Arrays.asList(ia)
and still there is a line saying:
Of course, some List operations aren't allowed on the wrapper, like adding or removing elements from the list, you can only read or overwrite the elements.
If list2 has a reference of List Interface, I expect it to implement ALL methods included in List interface in Java. https://docs.oracle.com/javase/7/docs/api/java/util/List.html.
add(int index, E element)
and
remove(int index)
show in List interface, so how is it possible that they are not implemented in list2?
I would have expected that list2
is a List; and thus I could call all methods belonging to the List interface?! So why are there exceptions thrown when calling add()
or remove()
?
There is a subtle detail here that is probably easy to miss:
The Arrays.asList() javadoc briefly mentions:
Returns a fixed-size list backed by the specified array.
In other words: yes, you receive something that says "I am a List"; but in fact, the underlying implementation gives you something we would call an structurally immutable list object. Thus all the methods that would change the structure of that specific list ... are "disabled" (by throwing exceptions at the call). You can still call set()
though to change elements within that list.
Long story short: the purpose of this method is not to give you a fully List-supporting object. The purpose of this method is to allow you to quickly create a fixed "list" of objects.
And more of personal opinion: I agree, this is actually not "consistent". I would have expected that either a completely immutable list would be returned; instead of some "half-baked" "structurally immutable".
It returns java.util.Arrays.ArrayList
which is fixed-size list
not java.util.ArrayList
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