How to clone ArrayList and also clone its contents?

后端 未结 21 1910
小鲜肉
小鲜肉 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:01

    The other posters are correct: you need to iterate the list and copy into a new list.

    However... If the objects in the list are immutable - you don't need to clone them. If your object has a complex object graph - they will need to be immutable as well.

    The other benefit of immutability is that they are threadsafe as well.

提交回复
热议问题