How to clone ArrayList and also clone its contents?

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

    All standard collections have copy constructors. Use them.

    List original = // some list
    List copy = new ArrayList(original); //This does a shallow copy
    

    clone() was designed with several mistakes (see this question), so it's best to avoid it.

    From Effective Java 2nd Edition, Item 11: Override clone judiciously

    Given all of the problems associated with Cloneable, it’s safe to say that other interfaces should not extend it, and that classes designed for inheritance (Item 17) should not implement it. Because of its many shortcomings, some expert programmers simply choose never to override the clone method and never to invoke it except, perhaps, to copy arrays. If you design a class for inheritance, be aware that if you choose not to provide a well-behaved protected clone method, it will be impossible for subclasses to implement Cloneable.

    This book also describes the many advantages copy constructors have over Cloneable/clone.

    • They don't rely on a risk-prone extralinguistic object creation mechanism
    • They don't demand unenforceable adherence to thinly documented conventions
    • They don't conflict with the proper use of final fields
    • They don't throw unnecessary checked exceptions
    • They don't require casts.

    Consider another benefit of using copy constructors: Suppose you have a HashSet s, and you want to copy it as a TreeSet. The clone method can’t offer this functionality, but it’s easy with a conversion constructor: new TreeSet(s).

提交回复
热议问题