In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly introduces the relevant knowledge of "how to realize the deep copy and shallow copy of Java". The editor shows you the operation process through an actual case. The operation method is simple, fast and practical. I hope this article "how to realize the deep copy and shallow copy of Java" can help you solve the problem.
With regard to deep and shallow copies of Java, it is simply to create an object that is exactly the same as a known object. It may not be used much in the daily coding process, but this is a question often asked by interviews, and you will have a better understanding of the so-called value passing or reference passing in Java by understanding the principles of deep and shallow copies.
1. Five ways to create an object: ①, through the new keyword
This is the most common way to create an object by calling the class's parameter or no-parameter constructor through the new keyword. For example, Object obj = new Object ()
②, through the newInstance () method of the Class class
The default is to call the no-parameter constructor of the class to create the object. For example, Person p2 = (Person) Class.forName ("com.ys.test.Person") .newInstance ()
③, through the newInstance method of the Constructor class
This and the second method class are implemented through reflection. The object is created by specifying a constructor through the newInstance () method of the java.lang.relect.Constructor class.
Person p3 = (Person) Person.class.getConstructors () [0] .newInstance ()
In fact, the second method uses the newInstance () method of Class to create an object, and its internal call is still the newInstance () method of Constructor.
④, using Clone method
Clone is a method in the Object class, through the object A.clone () method will create an object that is exactly the same as the object A, which is, as the name implies, to create an identical object.
Person p4 = (Person) p3.clone ()
⑤, deserialization
Serialization is to store the Java object data in heap memory in some way to disk files or pass them to other network nodes (transferred over the network). Deserialization is the process of restoring the object data in disk files or the object data on network nodes to Java object model.
You can refer to my blog post on how to implement it.
2. Clone method
In this blog, we talk about deep and shallow copies of Java, which are implemented by calling the clone () method of the Object class. In the Object.class class, the source code is:
Protected native Object clone () throws CloneNotSupportedException
This is a method modified with the native keyword, there is a blog about the native keyword, it doesn't matter if you don't understand it, you just need to know that the way to modify it with native is to tell the operating system, I don't realize this method, let the operating system realize it. We don't need to know exactly how to implement it, we just need to know that the function of the clone method is to copy the object and produce a new object. So what is the relationship between this new object and the original object?
3. Basic types and reference types
Here is another concept to popularize, the difference between basic types and reference types in Java.
In Java, data types can be divided into two main categories: basic types and reference types.
Basic types, also known as value types, are character types char, Boolean types boolean, and numeric types byte, short, int, long, float, double.
Reference types include classes, interfaces, arrays, enumerations, and so on.
Java divides memory space into heaps and stacks. The basic type stores the value directly in the stack, while the reference type puts the reference on the stack, and the actual stored value is placed in the heap, pointing to the data stored in the heap through the reference in the stack.
The an and b defined in the figure above are basic types whose values are stored directly in the stack, while c and d are declared by String, which is a reference type, the reference address is stored in the stack, and then points to the memory space of the heap.
The following d = c; this statement means that a reference to c is assigned to d, then c and d will point to the same heap memory space.
4. Shallow copy
Let's take a look at the following code:
Package com.ys.test;public class Person implements Cloneable {public String pname; public int page; public Address address; public Person () {} public Person (String pname,int page) {this.pname = pname; this.page = page; this.address = new Address ();} @ Override protected Object clone () throws CloneNotSupportedException {return super.clone () } public void setAddress (String provices,String city) {address.setAddress (provices, city);} public void display (String name) {System.out.println (name+ ":" + "pname=" + pname + ", page=" + page + "," + address);} public String getPname () {return pname;} public void setPname (String pname) {this.pname = pname } public int getPage () {return page;} public void setPage (int page) {this.page = page;}} package com.ys.test;public class Address {private String provices; private String city; public void setAddress (String provices,String city) {this.provices = provices; this.city = city @ Override public String toString () {return "Address [provices=" + provices + ", city=" + city + "]";}}
This is a primitive class Person that we want to assign. Let's generate a Person object and call its clone method to copy a new object.
Note: to call the object's clone method, you must have the class implement the Cloneable interface and override the clone method.
Test:
@ Testpublic void testShallowClone () throws Exception {Person p1 = new Person ("zhangsan", 21); p1.setAddress ("Hubei Province", "Wuhan"); Person p2 = (Person) p1.clone (); System.out.println ("p1:" + p1); System.out.println ("p1.getPname:" + p1.getPname (). HashCode ()); System.out.println ("p2:" + p2) System.out.println ("p2.getPname:" + p2.getPname (). HashCode ()); p1.display ("p1"); p2.display ("p2"); p2.setAddress ("Hubei Province", "Jingzhou"); System.out.println ("change the address of the copied object:"); p1.display ("p1"); p2.display ("p2");}
The print result is as follows:
First, look at the original class Person, which implements the Cloneable interface and overrides the clone method, which also has three properties, a pname defined by the reference type String, a page defined by the base type int, and a reference type Address, which is a custom class that also contains two properties, pprovices and city.
Then look at the test content. First, we create a Person class object p1, whose pname is zhangsan,page 21, and the address class Address attributes are Hubei Province and Wuhan City. Then we call the clone () method to copy another object, p2, and then print the contents of those two objects.
Print the results from lines 1 and 3:
P1:com.ys.test.Person@349319f9
P2:com.ys.test.Person@258e4566
You can see that these are two different objects.
From the object content printed on lines 5 and 6, the original object p1 and the cloned object p2 are exactly the same.
In the code, we just change the attribute Address of the cloned object p2 to Jingzhou City, Hubei Province (the original object p1 is Wuhan City, Hubei Province), but from the printing results on lines 7 and 8, the Address properties of the original object p1 and the cloned object p2 have been modified.
That is to say, the property Address of the object Person, after clone, only copies its reference, and they point to the same heap memory space. When you modify the property Address of one object, the other will also change.
Shallow copy: create a new object, then copy the non-static field of the current object to the new object, if the field is a value type, copy the field; if the field is a reference type, copy the reference but not the referenced object. Therefore, the original object and its copy refer to the same object.
5. Deep copy
If you figure out the shallow copy, then the deep copy is easy to understand.
Deep copy: create a new object and then copy the non-static field of the current object to the new object, regardless of whether the field is of value type or reference type. When you modify any of the contents of one object, it does not affect the contents of the other object.
So how to achieve deep copy? The clone provided by the Object class can only implement a shallow copy.
6. How to achieve deep copy?
We know the principle of deep copy, which is to make the reference type properties of the original object and the cloned object not point to the same heap memory. Here are three ways to implement it.
① to override the clone () method inside each reference type property
Since reference types cannot be deeply copied, we split each reference type into basic types and make shallow copies separately. For example, in the above example, the Person class has a reference type Address (actually String is also a reference type, but the String type is a bit special, which will be explained in more detail later), and we also override the clone method inside the Address class. As follows:
Address.class:
Package com.ys.test;public class Address implements Cloneable {private String provices; private String city; public void setAddress (String provices,String city) {this.provices = provices; this.city = city;} @ Override public String toString () {return "Address [provices=" + provices + ", city=" + city + "]"; @ Override protected Object clone () throws CloneNotSupportedException {return super.clone ();}}
The clone () method of Person.class:
@ Override protected Object clone () throws CloneNotSupportedException {Person p = (Person) super.clone (); p.address = (Address) address.clone (); return p;}
The test is the same as above, and we will find that the Address property of the p2 object has been changed, and the Address property of the p1 object has not changed.
But there is a drawback. Here our Person class has only one Address reference type, but the Address class does not, so we only need to override the clone method of the Address class, but if the Address class also has a reference type, then we also have to rewrite its clone method. If we go on like this, we have to rewrite how many reference types there are. If there are many reference types, then the amount of code will obviously be very large. So this method is not appropriate.
②, using serialization
Serialization is writing the object to the stream for easy transmission, while deserialization is reading the object out of the stream. The object written here in the stream is a copy of the original object, because the original object still exists in the JVM, so we can use the serialization of the object to generate a cloned object, and then deserialize it.
Note that every class that needs to be serialized implements the Serializable interface, and if there is a property that does not need serialization, you can declare it as transient, that is, excluding it from the clone property.
/ / Deep copy public Object deepClone () throws Exception {/ / serialize ByteArrayOutputStream bos = new ByteArrayOutputStream (); ObjectOutputStream oos = new ObjectOutputStream (bos); oos.writeObject (this); / / deserialize ByteArrayInputStream bis = new ByteArrayInputStream (bos.toByteArray ()); ObjectInputStream ois = new ObjectInputStream (bis); return ois.readObject ();}
Because serialization produces two completely independent objects, serialization can be deeply copied no matter how many reference types are nested.
This is the end of the content about "how to achieve deep copy and shallow copy of Java". Thank you for your reading. If you want to know more about the industry, you can follow the industry information channel. The editor will update different knowledge points for you every day.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.