Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Arrays.asList() return its own ArrayList implementation

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 ?

like image 686
Simeon Avatar asked Jan 11 '11 14:01

Simeon


People also ask

Is Arrays asList same as ArrayList?

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.

What does array asList return?

asList returns a fixed-size list that is​ backed by the specified array; the returned list is serializable and allows random access.

What does Arrays asList () do?

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.

Does Arrays asList create a new list?

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.


2 Answers

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:

  • performance: no need to copy anyting
  • memory efficent: no second array is needed
like image 159
Ralph Avatar answered Sep 23 '22 05:09

Ralph


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.

like image 29
sblundy Avatar answered Sep 19 '22 05:09

sblundy