How to clone ArrayList and also clone its contents?

后端 未结 21 1928
小鲜肉
小鲜肉 2020-11-21 06:42

How can I clone an ArrayList and also clone its items in Java?

For example I have:

ArrayList dogs = getDogs();
ArrayList

        
21条回答
  •  失恋的感觉
    2020-11-21 07:17

    Basically there are three ways without iterating manually,

    1 Using constructor

    ArrayList dogs = getDogs();
    ArrayList clonedList = new ArrayList(dogs);
    

    2 Using addAll(Collection c)

    ArrayList dogs = getDogs();
    ArrayList clonedList = new ArrayList();
    clonedList.addAll(dogs);
    

    3 Using addAll(int index, Collection c) method with int parameter

    ArrayList dogs = getDogs();
    ArrayList clonedList = new ArrayList();
    clonedList.addAll(0, dogs);
    

    NB : The behavior of these operations will be undefined if the specified collection is modified while the operation is in progress.

提交回复
热议问题