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

后端 未结 6 492
小蘑菇
小蘑菇 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:59

    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

提交回复
热议问题