Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is Java shallow copy and deep copy

2025-02-22 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains "what is Java shallow copy and deep copy". The content of the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "what is Java shallow copy and deep copy".

problem

"if you have an object and want to make an exact copy of it, how do you do it? first, you must create a new object that belongs to the same class. then you must iterate through all the member variables of the original object and copy the member variable values to the new object.

For (int I = 0; I

< 10; i++) { Sheep sheep = new Sheep("肖恩"+i+"号",2+i,"白色"); System.out.println(sheep.toString()); } 这种方式是比较容易想到的,但是有几个不足 在创建新对象的时候,总是需要重新获取原始对象的属性,如果创建的对象比较复杂,效率会很低 总是需要重新初始化对象,而不是动态地获得对象运行时的状态, 不够灵活 另一方面,并非所有对象都能通过这种方式进行复制, 因为有些对象可能拥有私有成员变量, 它们在对象本身以外是不可见的 "万物兼对象的 Java 中的所有类的根类 Object,提供了一个 clone() 方法,该方法可以将一个 Java 对象复制一份,但是需要实现 clone() 的类必须要实现一个接口 Cloneable,该接口表示该类能够复制且具有复制的能力。这就引出了原型模式。 基本介绍 原型模式(Prototype模式)是指:用原型实例指定创建对象的种类,并且通过拷贝这些原型,创建新的对象 原型模式是一种创建型设计模式, 使你能够复制已有对象, 而又无需使代码依赖它们所属的类 工作原理是:通过将一个原型对象传给那个要发动创建的对象,这个要发动创建的对象通过请求原型对象拷贝它们自己来实施创建,即 对象**.clone**() 类图

Prototype: the Prototype interface declares the cloning method

The Prototype class in Java needs to have the following two conditions

Implement the Cloneable interface. There is a Cloneable interface in the Java language, which serves only one purpose, which is to inform the virtual machine at run time that the clone method can be safely used on the class that implements this interface. In the Java virtual machine, only classes that implement this interface can be copied, otherwise a CloneNotSupportedException exception will be thrown at run time

Override the clone method in the Object class. In Java, the parent class of all classes is the Object class, and there is a clone method in the Object class that returns a copy of the object.

ConcretePrototype: the concrete ConcretePrototype class implements the cloning method. In addition to copying the data of the original object into the clone, this method sometimes needs to deal with the extreme cases of the cloning process, such as cloning associated objects and combing recursive dependencies.

Client: a client that uses a prototype first acquires the prototype instance object, and then clones itself through the prototype instance to create a new object.

Example

"Let's write this example with the example of Wang Erxiao herding sheep.

1. Prototype class (implementing Clonable)

Setter @ Getter @ NoArgsConstructor @ AllArgsConstructor class Sheep implements Cloneable {private String name; private Integer age; private String color; @ Override protected Sheep clone () {Sheep sheep = null; try {sheep = (Sheep) super.clone ();} catch (Exception e) {System.out.println (e.getMessage ());} return sheep;}}

2. Concrete prototype

Implement different prototype objects according to different business. Suppose the protagonist is Wang Erxiao, and there are a large flock of goats and sheep in the flock.

Public class Goat extends Sheep {public void graze () {System.out.println ("goat grazing");} public class Lamb extends Sheep {public void graze () {System.out.println ("lamb grazing");}}

3. Client

Public class Client {static List sheepList = new ArrayList (); public static void main (String [] args) {Goat goat = new Goat (); goat.setName ("goat"); goat.setAge (3); goat.setColor ("gray"); for (int I = 0; I < 5; iSum +) {sheepList.add (goat.clone ()) } Lamb lamb = new Lamb (); lamb.setName (Lamb); lamb.setAge (2); lamb.setColor (White); for (int I = 0; I < 5; iTunes +) {sheepList.add (lamb.clone ()); System.out.println (lamb.hashCode () + "," + lamb.clone (). HashCode () } for (Sheep sheep: sheepList) {System.out.println (sheep.toString ());}}

The prototype pattern delegates the cloning process to the actual object being cloned. The pattern declares a common interface for all objects that support cloning, which allows you to clone objects without coupling the code to the class to which the object belongs. Typically, there is only one clone method in such an interface.

All classes have very similar implementations of cloning methods. This method creates an object of the current class and then copies the values of all member variables of the original object to the new class. You can even copy private member variables because most programming languages allow objects to access private member variables of objects of their own kind.

Objects that support cloning are prototypes. When your object has dozens of member variables and hundreds of types, cloning it can even replace the construction of subclasses.

advantage

Creating an object using prototype mode is much better than new an object directly, because the clone method of the Object class is a native method that directly manipulates binary streams in memory, especially when copying large objects.

Another benefit of using the prototype pattern is that it simplifies the creation of objects, making them as simple as copying and pasting when we edit a document.

Because of the above advantages, you can consider using the prototype pattern when you need to create similar objects repeatedly. For example, if you need to create an object in a loop, if the object creation process is complex or there are many loops, using the prototype pattern can not only simplify the creation process, but also improve the overall performance of the system.

Applicable scenario

The "Head First design pattern" describes the prototype pattern as follows: when the process of creating an instance of a given class is expensive or complex, the prototype pattern is used.

If you need to copy some objects and want the code to be independent of the specific class to which the objects belong, you can use the prototype pattern.

If the difference between subclasses lies only in how their objects are initialized, you can use this pattern to reduce the number of subclasses. Others may create these subclasses in order to create specific types of objects

Application of prototype pattern in Spring

We all know that Spring bean is singleton by default, but some scenarios may require prototype scope, as follows

Similarly, Wang Erxiao still has 10 sheep, and those who are interested can also see if they create the same object.

Public class Client {public static void main (String [] args) {ApplicationContext context = new ClassPathXmlApplicationContext ("applicationContext.xml"); for (int I = 0; I < 10; iTunes +) {Object bean = context.getBean ("sheep"); System.out.println (bean);}

Interested students can go deep into the source code to take a look at the specific implementation, in the doGetBean () method of AbstractBeanFactory

Considerations for prototype pattern

Copying an object using prototype mode does not call the constructor of the class. Because the copy of the object is done by calling the clone method of the Object class, it copies the data directly in memory, so the constructor of the class is not called. Not only does the code in the constructor not execute, but even access permissions are not valid for the prototype pattern. Remember the singleton pattern? In singleton mode, a singleton can be implemented as long as the access permission of the constructor is set to private. However, the clone method directly ignores the permissions of the constructor, so the singleton pattern conflicts with the prototype pattern, and special attention should be paid when using it.

Deep copy and shallow copy. The clone method of the Object class copies only the basic data types in the object, but not arrays, container objects, reference objects, and so on. If you want to make a deep copy, you must make a separate copy of the array, container object, reference object, and so on, in the prototype pattern.

Shallow copy and deep copy

First of all, it is important to understand that both shallow and deep copies are operations on an existing object.

In Java, in addition to the basic data type (metatype), there is also an instance object of the class, which is a reference data type. And generally use the "=" sign to do the assignment operation. For the basic data type, it is actually a copy of its value, but for an object, the assignment is only a reference to the object, passing a reference to the original object, and they are actually pointing to the same object.

The distinction between shallow copy and deep copy is made on this basis. If when copying this object, only the basic data type is copied, and the reference data type is only transferred by reference. If a new object is not actually created, it is considered a shallow copy. Conversely, when you copy the reference data type, a new object is created and the member variables in it are copied, which is considered a deep copy.

"the so-called shallow copy and deep copy are just different operations on the reference data type of the instance object of the class when copying the object.

Shallow copy

For member variables whose data type is the basic data type, the shallow copy passes the value directly, that is, a copy of the property value is copied to the new object.

For a member variable whose data type is a reference data type, for example, a member variable is an array, an object of a class, etc., then a shallow copy will pass the reference, that is, just copy the reference value (memory address) of the member variable to the new object. Because in fact, the member variable of both objects points to the same instance. In this case, modifying the member variable in one object affects the value of the member variable in another object.

Before we cloned the sheep is a shallow copy, if we add an object type attribute to the Sheep, public Sheep child; can see that the friend of s and S1 is the same.

Sheep s = new Sheep (); s.setName ("sss"); s.friend = new Sheep (); s.friend.setName ("jubilant"); Sheep S1 = s.clone (); System.out.println (s = = S1); System.out.println (s.hashCode () + "- -" + s.clone (). HashCode ()); System.out.println (s.friend = = s1.friend) System.out.println (s.friend.hashCode () + "- -" + s1.friend.hashCode ()); false 621009875 false 1265094477 true 2125039532 Murray 2125039532

Deep copy

Now we know that the clone () method can only make a shallow copy of the current object, and the reference type is still passing the reference. So how to make a deep copy?

There are two common deep copy implementations:

Override the clone method to achieve deep copy

Deep copy through object serialization

Shallow copy and deep copy are relative. If there is only a basic data type inside an object, then the clone () method gets a deep copy of the object, while if there is a reference data type inside it, using the clone () method is a shallow copy operation.

Thank you for your reading, the above is the content of "what is Java shallow copy and deep copy". After the study of this article, I believe you have a deeper understanding of what is Java shallow copy and deep copy, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report