Java addAll(collection) vs new ArrayList(collection)

前端 未结 3 732
我寻月下人不归
我寻月下人不归 2021-01-08 00:08

Why do i get different behaviors with:

  1. Collection col2 = new ArrayList(col);

  2. Collection col2 = new ArrayList();

3条回答
  •  旧巷少年郎
    2021-01-08 00:59

    Collection col2 = new ArrayList(col);
    

    will create a new ArrayList with size col.size() (+10%) and copy all elements from col into that array.

    Collection col2 = new ArrayList();
    

    will create a new ArrayList with initial size of 10 (at least in Sun implementation).

    col2.addAll(col);
    

    will copy all elements from col into the end of the col2 ArrayList, enlarging the backing array size, if needed.

    So, depending on your col collection size, the behavior will be a bit different, but not too much.

    It is preferable to use the first option - that will avoid at least one extra backing array expansion operation.

提交回复
热议问题