In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-30 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly introduces "how to understand the shallow copy and deep copy of Java". In the daily operation, I believe many people have doubts about how to understand the shallow copy and deep copy of Java. The editor consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful to answer the questions of "how to understand the shallow copy and deep copy of Java". Next, please follow the editor to study!
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 is similar to the second method, which is achieved 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.
2. Clone method
In the Object.class class, the source code is:
Protected native Object clone () throws CloneNotSupportedException
This is a method modified with 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
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
Before we talk about shallow copy, let's use a piece of code to implement it.
The above code 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.
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.bowen.demo.demo008.method1.Person@5dfe23e8 p2:com.bowen.demo.demo008.method1.Person@583fb274
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 two ways to implement it.
Method 1: 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:
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.
Method 2: use 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.
Because serialization produces two completely independent objects, serialization can make a deep copy no matter how many reference types are nested.
At this point, the study on "how to understand the shallow copy and deep copy of Java" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
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.