java clone method example

// ipconfig | findstr "IPv4"
// soapui cracker:
<[http://download.csdn.net/download/tonyluo23/8014727]>

// json objects and arrays:
<[http://www.cnblogs.com/zhangji/archive/2011/09/02/2163811.html]>
<[https://msdn.microsoft.com/zh-cn/library/ie/cc836459(v=vs.94).aspx]>
<[https://msdn.microsoft.com/zh-cn/library/ie/cc836466(v=vs.94).aspx]>
<[https://msdn.microsoft.com/zh-cn/library/ie/htbw4ywd(v=vs.94).aspx]>
<[http://blog.csdn.net/column/details/step-to-oracle.html]>

package com.qingyuan.server;

import java.io.Serializable;

public class Car implements Serializable
{
    /** serialVersionUID */
    private static final long serialVersionUID = 4539772529921666906L;

    private String brand;
    
    private int price;
    
    public String getBrand()
    {
        return brand;
    }
    
    public void setBrand(String brand)
    {
        this.brand = brand;
    }
    
    public int getPrice()
    {
        return price;
    }
    
    public void setPrice(int price)
    {
        this.price = price;
    }
    
    public Object clone()
    {
        Car car = null;
        
        try
        {
            car = (Car) super.clone();
        }
        catch (CloneNotSupportedException e)
        {
            e.printStackTrace ();
        }
        
        return car;

    }
}

package com.qingyuan.server;

public class Person implements Cloneable
{
    private String name;
    
    private Car car;

    public String getName()
    {
        return name;
    }

    public void setName(String name)
    {
        this.name = name;
    }

    public Car getCar()
    {
        return car;
    }

    public void setCar(Car car)
    {
        this.car = car;
    }
    
    public Object clone()
    {
        Person person = null;
        try
        {
            person = (Person) super.clone();
        }
        catch (CloneNotSupportedException e)
        {
            e.printStackTrace ();
        }
        
        return person;
    }
}

package com.qingyuan.server;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * <[java shallow copy and deep copy -> deep copy: detached from the original object to the greatest extent]>
 * The copy method in Java is divided into deep copy and shallow copy. Simply put, a deep copy is to copy all the values ​​in an object, if there are references to other objects in the copied object,
 * then the object pointed to by this reference will itself be recreated. Shallow copy is similar to deep copy, but if there is a reference to other objects in the copied object, only this reference will
 * is copied, not the referenced object
 *
 * http://kuangbaoxu.iteye.com/blog/193222
 * http://stackoverflow.com/questions/2589741/how-to-effectively-copy-an-array-in-java
 * http://stackoverflow.com/questions/18638743/is-it-better-to-use-system-arraycopy-than-a-fast-for-loop-for-copying-array
 *
 * public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType)
 * Object[] foo = new Object[]{...};
 * String[] bar = new String[foo.length];
 * System.arraycopy(foo, 0, bar, 0, bar.length);
 *
 * "A variable of reference type" is called a pointer [pointer variable and the object pointed to by the pointer variable]
 * Suppose the following simple statement is written in the function: StringBuffer str = new StringBuffer("newString");
 * 1) : new StringBuffer("newString") applies for a piece of memory in the heap, and puts the created StringBuffer object into it;
 * 2) : String str declares a pointer, which is stored on the stack [because the statement is written in the function], which can be used to point to an object of type StringBuffer, or in other words, this pointer can be used to save a certain
 * the address of the StringBuffer object;
 * 3) : StringBuffer str = new StringBuffer("newString"); Save the memory address just applied for as the value of str;
 * StringBuffer str2 = str
 * In fact, the address of str is copied to str2, which is the copy of the address, and the StringBuffer object itself is not copied. So both pointers point to the same
 *
 * In fact, the value of the two pointers is the same, it must point to the same object (so the object content must be the same). But two objects with the same content,
 * Their addresses may be different (for example, between multiple cloned objects, the addresses are different)
 *
 * Problems with final constants:
 * The final modifier for reference type variables is also a source of confusion for many people. In fact, final just modifies the value of the pointer (that is, the address saved by the pointer cannot be changed)
 * As for the object pointed to by the pointer, it doesn't matter whether the content can be changed, so, for the following statement:
 * final StringBuffer strConst = new StringBuffer();
 * You can modify the content of the object it points to, for example: strConst.append("");
 * But its value cannot be modified, for example: strConst = null;
 */
/**
 * reference: <[http://www.bdqn.cn/news/201306/9459.shtml]>
 */
public class SystemCopy
{
    /*
     * The focus is on Person person2 = person1; in this sentence, person1 includes a reference to the Car object,
     * So is this sentence a deep copy or a shallow copy? The answer is nothing. It's just a simple pass by reference, after executing this sentence,
     * both person1 and person2 point to the same person object, so no matter who changes the object, another reference calls the object
     * value will change
     */
    /*   public static void main(String[] args)
    {
        Car car1 = new Car();
        car1.setBrand("BMW");
        car1.setPrice(10000);
        Person person1 = new Person();
        person1.setCar(car1);
        person1.setName("person1");
        Person person2 = person1;
        person2.setName("person2");
        System.out.println(person1.getName()); // person2
        System.out.println(person2.getName()); // person2
        Car car2 = new Car();
        car2.setBrand("Benz");
        car2.setPrice(20000);
        person1.setCar(car2);
        System.out.println(person2.getCar().getBrand()); // Benz
        System.out.println(person2.getCar().getPrice()); // 20000   
    }*/
    
    /**
     * The Car class remains unchanged, Person implements the Cloneable interface, then overloads the clone method of the parent class, and directly calls super.clone()
     * method to copy. But it is worth noting that the clone of the parent class is only a shallow copy, so there will be the above output results. So, in order to achieve deep copy
     *Baby, what do I need to do? In fact, the answer is already obvious, because clone is a shallow copy, and Car is a variable of primitive type, so we
     * Just let the Car class also implement the Cloneable interface, then overload the clone method, and then return to the Person class. When clone, add
     * car = car.clone() will do
     * @throws IOException
     * @throws ClassNotFoundException
     */
    /*  public static void main(String[] args)
    {
        Car car1 = new Car();
        car1.setBrand("BMW");
        car1.setPrice(10000);
        
        Person originalPerson = new Person();
        originalPerson.setCar(car1);
        originalPerson.setName("originalPerson");
        Person clonePerson = (Person)originalPerson.clone();
        
        originalPerson.setName("originalPerson_1");
        originalPerson.getCar().setBrand("Benz");
        
        System.out.println(originalPerson.getName());
        System.out.println(originalPerson.getCar().getBrand());
        System.out.println(clonePerson.getName());
        System.out.println(clonePerson.getCar().getBrand());
    }*/
    
    /**
     * Let the Car class implement the Serializable interface so that it can be serialized, and then you can use java's Io to transfer objects, and serialization can achieve the purpose of deep copying
     * The reason is that it first persists the entire object, then reads it all out, and gets a brand new copy every time it is read out, serialization is less efficient than cloneable,
     * When to use a shallow copy and when to use a deep copy, the answer is that if an object only contains variables of the original type, then use a shallow copy, if the class has
     * References to other classes, but other classes are immutable, still use shallow copy, if there are references to other classes, and other classes can be modified, you have to
     * deep copy;
     */
    public static void main(String[] args) throws IOException, ClassNotFoundException
    {
        Car originalCar = new Car();
        originalCar.setBrand("BMW");
        originalCar.setPrice(500000);
        
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
        objectOutputStream.writeObject(originalCar);
        objectOutputStream.flush();
        
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
        ObjectInputStream  objectInputStream = new ObjectInputStream(byteArrayInputStream);
        
        Car cloneCar = (Car) objectInputStream.readObject();
        
        System.out.println(cloneCar.getBrand());   // BMW
        System.out.println(cloneCar.getPrice());    // 500000
        
        cloneCar.setBrand("Honda");
        cloneCar.setPrice(3000);
        
        System.out.println(originalCar.getBrand()); // BMW
        System.out.println(originalCar.getPrice());  // 500000
        System.out.println(cloneCar.getBrand());    // Honda
        System.out.println(cloneCar.getPrice());     // 3000
    }
}

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=327057087&siteId=291194637