Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the return type of Arrays.asList?

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()?

like image 750
CrazySynthax Avatar asked Mar 09 '23 02:03

CrazySynthax


2 Answers

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".

like image 146
GhostCat Avatar answered Mar 19 '23 07:03

GhostCat


It returns java.util.Arrays.ArrayList which is fixed-size list

not java.util.ArrayList

like image 29
Basheer AL-MOMANI Avatar answered Mar 19 '23 07:03

Basheer AL-MOMANI