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
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Writing DTOs With Java8, Lombok, and Java14+
  • Redefining Java Object Equality
  • Addressing Memory Issues and Optimizing Code for Efficiency: Glide Case
  • Singleton: 6 Ways To Write and Use in Java Programming

Trending

  • Solid Testing Strategies for Salesforce Releases
  • Is Agile Right for Every Project? When To Use It and When To Avoid It
  • The 4 R’s of Pipeline Reliability: Designing Data Systems That Last
  • Comprehensive Guide to Property-Based Testing in Go: Principles and Implementation
  1. DZone
  2. Coding
  3. Languages
  4. Deep Clone Collection Objects in Java [Snippets]

Deep Clone Collection Objects in Java [Snippets]

Check out this post on how to deep clone an object in Java 8 using the Object.clone method and new Java streams.

By 
Yogen Rai user avatar
Yogen Rai
·
Jul. 18, 18 · Code Snippet
Likes (11)
Comment
Save
Tweet
Share
34.9K Views

Join the DZone community and get the full member experience.

Join For Free

Deep cloning of an object has always been something that Java developers work on constantly. There are a lot of articles that talk about the different ways to clone objects deeply and obviously. The preferred method is to use  Copy Constructors since it overcomes the design issues of  Object.clone() and provides better control over object construction.

Clone an Object

For example, if I want to have a deep copy of the Dog object, then I would use constructor as:

class Dog {
    private String name;
    private int age;

    public Dog(String name, int age) {
        super();
        this.name = name;
        this.age = age;
    }

    //copy constructor to create the copy of the Dog object
    public Dog(Dog dog) {
        this.name = dog.name;
        this.age = dog.age;
    }
    // getters and setters
}


Some of the notable advantages of using them over Objects.clone() are:

  • This doesn't force us to implement any interface or throw an exception, but we can surely do it if it is required.
  • This allows us to have complete control over object creation; we can write our initialization logic in it.

Clone a Collection

With new feature Streams introduced in Java 8, it has been the easiest ever to clone the collections, because when a stream is created, the instance will not modify its source. This allows the creation of multiple instances from a single source.     

For example, if the  List of Dogscan be cloned as below:

Dog dog1 = new Dog("Puppy", 4);
Dog dog2 = new Dog("Tom", 5);
Dog dog3 = new Dog("Hen", 3);
Dog dog4 = new Dog("Jen", 7);
List<Dog> dogs = new ArrayList<>();
dogs.add(dog1);
dogs.add(dog2);
dogs.add(dog3);
dogs.add(dog4);

//clone with java 8
List<Dog> clonedList = dogs.stream().map(Dog::new).collect(Collectors.toList());


Now, any modification you make to the original collection doesn't affect the cloned collection and vice-versa. 

//clone with java 8
List<Dog> clonedList = dogs.stream().map(Dog::new).collect(Collectors.toList());

assertThat(dogs, is(clonedList));

// modify original list
dogs.remove(0);
// make sure cloned list remains unaffected
assertEquals(3, dogs.size());
assertEquals(4, clonedList.size());

// modify cloned list
clonedList.add(new Dog("New", 3));
// make sure original list remains unaffected
assertEquals(3, dogs.size());
assertEquals(5, clonedList.size());

// modify element in dogs
dog2.setName("Very New Name");

assertEquals("Very New Name", dogs.get(0).getName());
assertEquals("Tom", clonedList.get(1).getName());

 

The source code for the example presented above is available on GitHub.

Object (computer science) Clone (Java method) Java (programming language)

Published at DZone with permission of Yogen Rai, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Writing DTOs With Java8, Lombok, and Java14+
  • Redefining Java Object Equality
  • Addressing Memory Issues and Optimizing Code for Efficiency: Glide Case
  • Singleton: 6 Ways To Write and Use in Java Programming

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!