How to clone ArrayList and also clone its contents?

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

    I, personally, would add a constructor to Dog:

    class Dog
    {
        public Dog()
        { ... } // Regular constructor
    
        public Dog(Dog dog) {
            // Copy all the fields of Dog.
        }
    }
    

    Then just iterate (as shown in Varkhan's answer):

    public static List cloneList(List dogList) {
        List clonedList = new ArrayList(dogList.size());
        for (Dog dog : dogList) {
            clonedList.add(new Dog(dog));
        }
        return clonedList;
    }
    

    I find the advantage of this is you don't need to screw around with the broken Cloneable stuff in Java. It also matches the way that you copy Java collections.

    Another option could be to write your own ICloneable interface and use that. That way you could write a generic method for cloning.

提交回复
热议问题