Cloning with generics

后端 未结 6 615
栀梦
栀梦 2020-12-08 17:19

Once upon a time there was a class:

public class Scope> implements Comparable>, Clon         


        
6条回答
  •  清歌不尽
    2020-12-08 17:37

    As you see, if a class tries to implement Cloneable and you want a deep clone, then all of your constituent objects needs to be immutable, primitive, or need to also be Cloneable.

    Often, a better and easier approach is to create a copy constructor.

    public class Scope> implements Comparable>, Serializable {
        private C starts;
        private C ends;
        public Scope(final Scope original) {
           starts = new C(original.starts);
           ends = new C(original.ends);
           // initialize all my other fields from "original"
        }
    }
    

    and of course you need a copy constructor on C that is capable of handling polymorphism.

    If you have no access or ability to modify the source to C, then any method of copying, no matter what the method, will be very difficult and potentially impossible. For example, it is not possible to make a copy of an enum instance.

提交回复
热议问题