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

How to understand shallow copy and deep copy in Java

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

Share

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

This article introduces how to understand the shallow copy and deep copy of Java. The content is very detailed. Interested friends can use it for reference. I hope it will be helpful to you.

Java shallow copy deep copy

Shallow and deep copies involve the clone () method in the Object class

Implement shallow copy

The implementation of shallow copy requires the class to override the clone () method.

A shallow copy creates a new object that has an exact copy of the original object property value.

If the attribute is a base type, the value of the base type is copied

If the property is a memory address (reference type), the memory address is copied, so if one object changes this address, it will affect the other object, resulting in unequal references between the two objects.

It is easy to implement a shallow copy simply by implementing the Cloneable interface of the class and overriding the clone method

Class Person implements Cloneable {String name; int age; public Person () {} public Person (String name, int age) {this.name = name; this.age = age;} public String getName () {return name;} public void setName (String name) {this.name = name;} public int getAge () {return age } public void setAge (int age) {this.age = age;} / * override the clone () method * * @ return * @ throws CloneNotSupportedException * / @ Override protected Object clone () throws CloneNotSupportedException {return super.clone () } @ Override public String toString () {return "Person {" + "name='" + name +'\'+ ", age=" + age +'}';}}

Test shallow copy characteristics

Public void testClone () throws CloneNotSupportedException {Person person1 = new Person (); person1.setName ("ccy"); person1.setAge (20); Person person2 = (Person) person1.clone (); / / View shallow copy effect System.out.println (person1); System.out.println (person2); System.out.println (person1.getName () = = person2.getName ()) / / verify the characteristics of clone () System.out.println (person1.clone ()! = person1); System.out.println (person1.clone (). GetClass () = = person1.getClass ()) / / if the basic type shallow copy directly assigned value, if the reference type shallow copy points to its memory address, that is, the shared memory address / / change the value of the reference type String property of person1, the reference will be changed person1.setName ("zfs"); System.out.println (person2.getName ());}

Achieve deep copy

For the above question, although the two objects copied are different, but some of the internal references are still the same, how to copy this object absolutely so that it is completely independent of the original object? Use our deep copy. Deep copy: when you copy the reference data type, a new object is created and the member variables in it are copied.

In the implementation of deep copy, there are two ways to rewrite the clone () method and the sequence method.

Override the clone () method

If you use the override clone () method to implement a deep copy, you will also implement the Cloneable interface to implement the clone () method for all classes in the class that have custom reference variables. For character classes, you can create a new string implementation copy. But for custom classes, you need to implement cloneable to override clone, which is too troublesome, so we use serialization

Serialization

After serialization, the binary byte stream is written to a medium (text or byte array), and then the data is read from this medium. The original object is written to this medium and copied to the clone object. The modification of the original object does not affect the clone object, because the clone object is read from this medium.

People familiar with object caching know that we often cache Java objects into Redis, and then possibly read and generate Java objects from Redis, which uses serialization and deserialization. Generally, Java objects can be stored as byte streams or json strings and then deserialized into Java objects. Because serialization stores the properties of the object, it does not and cannot store information about the address of the object in memory. So all reference objects are recreated when deserialized to Java objects.

In the concrete implementation, the custom class needs to implement the Serializable interface

Class Person implements Serializable {String name; int age; public Person () {} public Person (String name, int age) {this.name = name; this.age = age;} public String getName () {return name;} public void setName (String name) {this.name = name;} public int getAge () {return age } public void setAge (int age) {this.age = age;} @ Override public String toString () {return "Person {" + "name='" + name +'\'+ ", age=" + age +'}';} protected Person 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 (Person) ois.readObject ();}}

Testing method

Public void testClone () throws Exception {Person person1 = new Person (); person1.setName ("ccy"); person1.setAge (20); Person person2 = person1.deepClone (); System.out.println (person1.getName () = = person2.getName ());}

You can see that the addresses of the two reference objects are different, and the deep copy is successfully implemented.

About Java shallow copy and deep copy how to understand how to share here, I hope the above content can be of some help to you, can learn more knowledge. If you think the article is good, you can share it for more people to see.

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