How to clone ArrayList and also clone its contents?

后端 未结 21 2351
小鲜肉
小鲜肉 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条回答
  •  萌比男神i
    2020-11-21 06:59

    You will need to clone the ArrayList by hand (by iterating over it and copying each element to a new ArrayList), because clone() will not do it for you. Reason for this is that the objects contained in the ArrayList may not implement Clonable themselves.

    Edit: ... and that is exactly what Varkhan's code does.

提交回复
热议问题