How do you make a deep copy of an object?

前端 未结 19 1926
执念已碎
执念已碎 2020-11-21 23:09

It\'s a bit difficult to implement a deep object copy function. What steps you take to ensure the original object and the cloned one share no reference?

19条回答
  •  情歌与酒
    2020-11-21 23:57

    One way to implement deep copy is to add copy constructors to each associated class. A copy constructor takes an instance of 'this' as its single argument and copies all the values from it. Quite some work, but pretty straightforward and safe.

    EDIT: note that you don't need to use accessor methods to read fields. You can access all fields directly because the source instance is always of the same type as the instance with the copy constructor. Obvious but might be overlooked.

    Example:

    public class Order {
    
        private long number;
    
        public Order() {
        }
    
        /**
         * Copy constructor
         */
        public Order(Order source) {
            number = source.number;
        }
    }
    
    
    public class Customer {
    
        private String name;
        private List orders = new ArrayList();
    
        public Customer() {
        }
    
        /**
         * Copy constructor
         */
        public Customer(Customer source) {
            name = source.name;
            for (Order sourceOrder : source.orders) {
                orders.add(new Order(sourceOrder));
            }
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    }
    

    Edit: Note that when using copy constructors you need to know the runtime type of the object you are copying. With the above approach you cannot easily copy a mixed list (you might be able to do it with some reflection code).

提交回复
热议问题