Home Java javaTutorial What is the difference between shallow copy and deep copy in Java?

What is the difference between shallow copy and deep copy in Java?

Apr 11, 2024 pm 12:33 PM
apache Shallow copy deep copy

The difference between shallow copy and deep copy: Shallow copy: Create an object that references the same data, and changing the copy will also affect the original object. Deep copy: Create an object that contains a copy of the original object's data. Changing the copy will not affect the original object.

What is the difference between shallow copy and deep copy in Java?

Shallow copy and deep copy in Java

Introduction

In Java , understanding the concepts of shallow copy and deep copy is crucial for object operations. This tutorial details the differences between the two and illustrates them with code examples.

Shallow copy

  • Creates a new object that references the same underlying data of the original object.
  • Any changes to the shallow copy will also be reflected on the original object, and vice versa.
  • Follow the "reference to the same " principle.

Code example:

class Person {
    private String name;
    private Address address;
}

public class ShallowCopyDemo {

    public static void main(String[] args) {
        Person p1 = new Person();
        p1.setName("John Doe");
        Address addr = new Address();
        addr.setStreet("123 Main St.");
        p1.setAddress(addr);

        // Shallow copy
        Person p2 = p1;

        // 更改 p2 的地址
        p2.getAddress().setStreet("456 Elm St.");

        // p1 的地址也发生了变化
        System.out.println(p1.getAddress().getStreet()); // 输出:456 Elm St.
    }
}
Copy after login

In this example, p2 is a shallow copy of p1, they References the same Address object. Therefore, changes to the address of p2 will also affect p1.

Deep copy

  • Creates a new object that has an independent copy of the underlying data of the original object.
  • Changing the deep copy will not affect the original object and vice versa.
  • Follow the principle of "same content".

Code example:

Use the clone() method or a third-party library (such as Apache Commons Lang) to implement deep copy.

Using the clone() method:

class Person implements Cloneable {
    private String name;
    private Address address;

    @Override
    public Person clone() {
        try {
            // 使用 super.clone() 创建新对象
            return (Person) super.clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        return null;
    }
}

public class DeepCopyDemo {

    public static void main(String[] args) {
        Person p1 = new Person();
        p1.setName("John Doe");
        Address addr = new Address();
        addr.setStreet("123 Main St.");
        p1.setAddress(addr);

        // Deep copy
        Person p2 = p1.clone();

        // 更改 p2 的地址
        p2.getAddress().setStreet("456 Elm St.");

        // p1 的地址保持不变
        System.out.println(p1.getAddress().getStreet()); // 输出:123 Main St.
    }
}
Copy after login

In this example, the clone() method is created for p1 A deep copy. Changing the address of p2 will not affect p1 because they refer to different Address objects.

When to use deep copy or shallow copy?

  • Shallow copy: Shallow copy can be performed when there are no side effects on modifying the copy of the object.
  • Deep copy: When modifying the copy of the object may affect the original object, a deep copy must be made.

For example, be sure to use deep copies when caching objects or passing them to untrusted code.

The above is the detailed content of What is the difference between shallow copy and deep copy in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to set the cgi directory in apache How to set the cgi directory in apache Apr 13, 2025 pm 01:18 PM

To set up a CGI directory in Apache, you need to perform the following steps: Create a CGI directory such as "cgi-bin", and grant Apache write permissions. Add the "ScriptAlias" directive block in the Apache configuration file to map the CGI directory to the "/cgi-bin" URL. Restart Apache.

How to connect to the database of apache How to connect to the database of apache Apr 13, 2025 pm 01:03 PM

Apache connects to a database requires the following steps: Install the database driver. Configure the web.xml file to create a connection pool. Create a JDBC data source and specify the connection settings. Use the JDBC API to access the database from Java code, including getting connections, creating statements, binding parameters, executing queries or updates, and processing results.

What to do if the apache80 port is occupied What to do if the apache80 port is occupied Apr 13, 2025 pm 01:24 PM

When the Apache 80 port is occupied, the solution is as follows: find out the process that occupies the port and close it. Check the firewall settings to make sure Apache is not blocked. If the above method does not work, please reconfigure Apache to use a different port. Restart the Apache service.

How to view your apache version How to view your apache version Apr 13, 2025 pm 01:15 PM

There are 3 ways to view the version on the Apache server: via the command line (apachectl -v or apache2ctl -v), check the server status page (http://<server IP or domain name>/server-status), or view the Apache configuration file (ServerVersion: Apache/<version number>).

How to solve the problem that apache cannot be started How to solve the problem that apache cannot be started Apr 13, 2025 pm 01:21 PM

Apache cannot start because the following reasons may be: Configuration file syntax error. Conflict with other application ports. Permissions issue. Out of memory. Process deadlock. Daemon failure. SELinux permissions issues. Firewall problem. Software conflict.

How to view the apache version How to view the apache version Apr 13, 2025 pm 01:00 PM

How to view the Apache version? Start the Apache server: Use sudo service apache2 start to start the server. View version number: Use one of the following methods to view version: Command line: Run the apache2 -v command. Server Status Page: Access the default port of the Apache server (usually 80) in a web browser, and the version information is displayed at the bottom of the page.

How to start apache How to start apache Apr 13, 2025 pm 01:06 PM

The steps to start Apache are as follows: Install Apache (command: sudo apt-get install apache2 or download it from the official website) Start Apache (Linux: sudo systemctl start apache2; Windows: Right-click the "Apache2.4" service and select "Start") Check whether it has been started (Linux: sudo systemctl status apache2; Windows: Check the status of the "Apache2.4" service in the service manager) Enable boot automatically (optional, Linux: sudo systemctl

How to delete more than server names of apache How to delete more than server names of apache Apr 13, 2025 pm 01:09 PM

To delete an extra ServerName directive from Apache, you can take the following steps: Identify and delete the extra ServerName directive. Restart Apache to make the changes take effect. Check the configuration file to verify changes. Test the server to make sure the problem is resolved.

See all articles