DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Redefining Java Object Equality
  • Singleton: 6 Ways To Write and Use in Java Programming
  • Generics in Java and Their Implementation
  • Speeding Up Large Collections Processing in Java

Trending

  • Avoiding AI Debt as a Team
  • The Self-Hosting Math Changed While We Were Still Arguing About Sovereignty
  • Beyond the Wall of Charts: How Advanced Observability Displaced the Telemetry Dashboard
  • One Database, Two Models: Building AI-Friendly Java Applications With MySQL JSON Duality Views

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Coding
  3. Java
  4. Creating a Deep vs. Shallow Copy of an Object in Java

Creating a Deep vs. Shallow Copy of an Object in Java

There are two main ways to make copies: deep copy and shallow copy. Let’s explore these concepts and see how they work with some easy examples.

By 
Reza Ganji
DZone Core CORE ·
Sep. 05, 23 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
7.8K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

When working with objects in Java, there are times when you need to create a copy of an object. However, not all copies are the same. In fact, there are two main ways to make copies: deep copy and shallow copy. Let’s explore these concepts and see how they work with some easy examples.

Deep Copy: What Is It?

Imagine you have a collection of shapes, each with its own set of properties. A deep copy of an object means creating a completely new copy of the original object, along with all the nested objects it contains. In other words, it’s like making a photocopy of each shape, including all the details.

Shallow Copy: What's the Difference?

On the other hand, a shallow copy is like making a copy of a picture and its frame. You get a new frame, but the picture itself remains the same. Similarly, a shallow copy of an object creates a new object, but it still shares the same nested objects with the original. Changes made to nested objects in the copied object will also affect the original object, and vice versa.

Let’s Put It Into Practice: Shapes Example

Imagine you have a class called Circle, which has a nested object of class Point representing its center. We'll see how deep copy and shallow copy work with these objects.

Java
 
public class Circle {
   public Point center;
    public int radius;

    public Circle(Point center, int radius) {
        this.center = center;
        this.radius = radius;
    }
}

public class Point {
        public int x, y;

        public Point(int x, int y) {
            this.x = x;
            this.y = y;
        }
    }


Creating a Shallow Copy

For a shallow copy, we just copy the references to the nested objects:

Java
 
public Circle shallowCopyCircle(Circle original) {
        return new Circle(original.center, original.radius);
 }


Creating Deep Copy

For a deep copy of a Circle, we need to create new instances of both the Point and the Circle objects:

Java
 
 public Circle deepCopyCircle(Circle original) {
        Point copiedPoint = new Point(original.center.x, original.center.y);
        return new Circle(copiedPoint, original.radius);
  }


Creating Simple CopyUtil Class

Here is the util class which has object copy codes:

Java
 
public class CopyUtil {
    public Circle deepCopyCircle(Circle original) {
        Point copiedPoint = new Point(original.center.x, original.center.y);
        return new Circle(copiedPoint, original.radius);
    }
    public Circle shallowCopyCircle(Circle original) {
        return new Circle(original.center, original.radius);
    }
}


Unit Tests

Let's write some simple tests to check our deep copy and shallow copy methods.

Java
 
public class ShallowAndDeepCopyUnitTest {

    @Test
    public void givenCircle_whenDeepCopy_thenDifferentObjects() {
        CopyUtil util=new CopyUtil();
        Point center = new Point(3, 5);
        Circle original;
        original = new Circle(center, 10);
        Circle copied = util.deepCopyCircle(original);
        assertNotSame(original, copied);
        Assert.assertNotSame(original.center, copied.center);
    }

    @Test
    public void givenCircle_whenShallowCopy_thenSameCenter() {
        CopyUtil util=new CopyUtil();
        Point center = new Point(7, 9);
        Circle original = new Circle(center, 15);
        Circle copied = util.shallowCopyCircle(original);
        assertNotSame(original, copied);
        assertSame(original.center, copied.center);
    }
}


Conclusion

Creating deep copies and shallow copies of objects in Java is like making copies of pictures and their frames. Deep copies duplicate everything, while shallow copies create new frames but share the same pictures. By understanding these concepts and applying them in your Java programs, you can ensure that your objects are copied in the way that best suits your needs. So remember, whether it's circles, squares, or any other objects, knowing how to copy them can make your Java programming smoother and more efficient.

Java (programming language) Object (computer science) Data Types

Opinions expressed by DZone contributors are their own.

Related

  • Redefining Java Object Equality
  • Singleton: 6 Ways To Write and Use in Java Programming
  • Generics in Java and Their Implementation
  • Speeding Up Large Collections Processing in Java

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook