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 ?


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

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


    Arrays.asList需要返回一个无法调整大小的列表 - 因为底层数组无法调整大小 - 但是可以修改 - 因为可以对底层数组中的元素进行赋值。

    链接地址: http://www.djcxy.com/p/17622.html

    上一篇: 迭代集合,避免在循环中移除时出现ConcurrentModificationException

    下一篇: 为什么Arrays.asList()返回自己的ArrayList实现