How to clone ArrayList and also clone its contents?

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

    I think the current green answer is bad , why you might ask?

    • It can require to add a lot of code
    • It requires you to list all Lists to be copied and do this

    The way serialization is also bad imo, you might have to add Serializable all over the place.

    So what is the solution:

    Java Deep-Cloning library The cloning library is a small, open source (apache licence) java library which deep-clones objects. The objects don't have to implement the Cloneable interface. Effectivelly, this library can clone ANY java objects. It can be used i.e. in cache implementations if you don't want the cached object to be modified or whenever you want to create a deep copy of objects.

    Cloner cloner=new Cloner();
    XX clone = cloner.deepClone(someObjectOfTypeXX);
    

    Check it out at https://github.com/kostaskougios/cloning

提交回复
热议问题