How to clone ArrayList and also clone its contents?

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

    You will need to iterate on the items, and clone them one by one, putting the clones in your result array as you go.

    public static List cloneList(List list) {
        List clone = new ArrayList(list.size());
        for (Dog item : list) clone.add(item.clone());
        return clone;
    }
    

    For that to work, obviously, you will have to get your Dog class to implement the Cloneable interface and override the clone() method.

提交回复
热议问题