How to clone ArrayList and also clone its contents?

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

    The below worked for me..

    in Dog.java

    public Class Dog{
    
    private String a,b;
    
    public Dog(){} //no args constructor
    
    public Dog(Dog d){ // copy constructor
       this.a=d.a;
       this.b=d.b;
    }
    
    }
    
     -------------------------
    
     private List createCopy(List dogs) {
     List newDogsList= new ArrayList<>();
     if (CollectionUtils.isNotEmpty(dogs)) {
     dogs.stream().forEach(dog-> newDogsList.add((Dog) SerializationUtils.clone(dog)));
     }
     return newDogsList;
     }
    

    Here the new list which got created from createCopy method is created through SerializationUtils.clone(). So any change made to new list will not affect original list

提交回复
热议问题