Use of clone method

  Since Java has a quote, when two variables point to the same piece of memory, changing the value of one of them will also change the other variable. If we need to have two independent variables with the same content at the same time, we need to re-instantiate these two variables.
  The clone method has been implemented for some basic classes, such as ArrayList and so on. But there are still some classes that are not implemented. If we customize a class and want to call the clone method, we need to implement the Cloneable interface. The code is as follows:

  public class A implements Cloneable { 
    public String str; 
    public Object clone() { 
        A o = null; 
        try { 
            o = (A) super.clone(); 
        } catch (CloneNotSupportedException e) { 
            e.printStackTrace(); 
        } 
        return o; 
    } 
} In 

this way, we only need to call the clone method to copy a class with the same content. Use as follows:
A a1=new A(); 
A a2=(A)a1.clone();

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326393206&siteId=291194637