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

后端 未结 6 494
小蘑菇
小蘑菇 2020-12-02 12:55

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 d

6条回答
  •  庸人自扰
    2020-12-02 13:44

    Two comments:

    1, Attempting to shrink the returned array by calling the remove() method of List interface will throw an UnsupportedOperationException. This is because the inner ArrayList class inside of Arrays class extends AbstractList, and the remove() method in AbstractList throws UnsupportedException.

    Thus once the List is returned, you can overstore existing elements EITHER in the array OR in the returned List, BUT you are NOT permitted to grow the array or shrink the array.

    1. In response to:

      actually you are able to add elements to the ArrayList with add. method like this : List l2= new ArrayList(Arrays.asList(array1)); l2.add("blueCheese");

    The l2 is an independent copy of the list, so List l2 is now decoupled from the original array&List. So blueCheese in in l2, but not in the original array/List that were backed up from each other.

    -dbednar

提交回复
热议问题