Today, we suddenly used the most basic java value reference and value copy, as well as the object's shortest cloning and deep cloning. Don't go round. Let's look at the example directly.
Simple Type value reference, which also belongs to the value struct;
Int a = 3
Int B =
Then, no matter how a changes the value, the value of B will not change because of a, but the following example:
Student {
String name;
Int sex;
}
Student stu1 = new Student ();
Student stu2 = stu1;
Stu1.setName ("1122 ');
This value belongs to the object, but it is only a reference of the object.
In this case, the name in stu2 is also changed to 1122
If you do not want to be affected, use the following method:
Set
Student stu2 = stu1;
For
Student stu2 = null;
Beanutils. copePorperties (stu1, stu2); // The beanutils here is a class in spring.
This assignment is also called a shortest clone.
If Sturdent is referenced by an object in this class, the above method cannot solve the problem of changing attributes in the object. In this case, deep cloning is required.
For example:
Class Student {
String name;
Int sex;
Public List <Person> li;
}
If you need to change the value of the Person object in the property li in Student, and make other backups unaffected, you need to use the following method:
1 Student this class needs to implement the sequential call interface
2. Add a clone method.
The modified code is as follows:
Class Student implements Serializable {
String name;
Int sex;
Public List <Person> li;
Public Student deepClone (){
Studentdc = null;
Try {
ByteArrayOutputStream baos = new ByteArrayOutputStream ();
ObjectOutputStream oos = new ObjectOutputStream (baos );
Oos. writeObject (this );
Oos. close ();
ByteArrayInputStream bais = new ByteArrayInputStream (baos. toByteArray ());
ObjectInputStream bis = new ObjectInputStream (bais );
Dc = (Student) bis. readObject ();
} Catch (IOException e ){
E. printStackTrace ();
} Catch (ClassNotFoundException e ){
E. printStackTrace ();
}
Return dc;
}
You only need to perform the following operations:
Student stu1 = new Student ();
Stu2 = stu1.deepClone ();
Changing any value in stu1 does not affect the value in stu2.
Note that the Person class must also implement the serialization interface. Otherwise, an exception will be thrown during serialization of Student.
}