Skip to content
Fix Code Error

How do I copy an object in Java?

March 13, 2021 by Code Error
Posted By: Anonymous

Consider the code below:

DummyBean dum = new DummyBean();
dum.setDummy("foo");
System.out.println(dum.getDummy()); // prints 'foo'

DummyBean dumtwo = dum;
System.out.println(dumtwo.getDummy()); // prints 'foo'

dum.setDummy("bar");
System.out.println(dumtwo.getDummy()); // prints 'bar' but it should print 'foo'

So, I want to copy the dum to dumtwo and change dum without affecting the dumtwo. But the code above is not doing that. When I change something in dum, the same change is happening in dumtwo also.

I guess, when I say dumtwo = dum, Java copies the reference only. So, is there any way to create a fresh copy of dum and assign it to dumtwo?

Solution

Create a copy constructor:

class DummyBean {
  private String dummy;

  public DummyBean(DummyBean another) {
    this.dummy = another.dummy; // you can access  
  }
}

Every object has also a clone method which can be used to copy the object, but don’t use it. It’s way too easy to create a class and do improper clone method. If you are going to do that, read at least what Joshua Bloch has to say about it in Effective Java.

Answered By: Anonymous

Related Articles

  • How can I resolve Web Component Testing error?
  • Python is not calling fucntions properly
  • Unable to run Robolectric and Espresso with a…
  • Examples of GoF Design Patterns in Java's core libraries
  • TLS 1.3 server socket with Java 11 and self-signed…
  • Usage of __slots__?
  • When I'm testing a web app by JUnit and Mockito I…
  • What's the difference between eval, exec, and compile?
  • Eclipse will not start and I haven't changed anything
  • ClassNotFoundException:…
  • Neither BindingResult nor plain target object for…
  • What is your most productive shortcut with Vim?
  • How do SO_REUSEADDR and SO_REUSEPORT differ?
  • JUNIT @ParameterizedTest , Parameter resolution Exception
  • What is a NullReferenceException, and how do I fix it?
  • Jetpack Compose and Hilt Conflict
  • How does PHP 'foreach' actually work?
  • java IO Exception: Stream Closed
  • data.table vs dplyr: can one do something well the…
  • How can I manually compile a svelte component down…
  • SecurityException: Permission denied (missing…
  • Ukkonen's suffix tree algorithm in plain English
  • What does "Fatal error: Unexpectedly found nil while…
  • SQLException: No suitable Driver Found for…
  • How to filter a RecyclerView with a SearchView
  • For-each over an array in JavaScript
  • Gradle error: Execution failed for task…
  • Difference between variable declaration syntaxes in…
  • How to add Typescript to a Nativescript-Vue project?
  • Reference - What does this regex mean?
  • Requested bean is currently in creation: Is there an…
  • How to format a phone number in a textfield
  • How to convert number to words in java
  • Identifying and solving…
  • How do I install Java on Mac OSX allowing version switching?
  • How to convert java.util.Date to java.sql.Date?
  • Can't access Eclipse marketplace
  • Using enums in a spring entity
  • What are the undocumented features and limitations…
  • How to use Servlets and Ajax?
  • android studio 0.4.2: Gradle project sync failed error
  • Execution failed for task…
  • What is an optional value in Swift?
  • What does if __name__ == "__main__": do?
  • What's the difference between Instant and LocalDateTime?
  • org.gradle.api.tasks.TaskExecutionException:…
  • What does "Could not find or load main class" mean?
  • javax.faces.application.ViewExpiredException: View…
  • Understanding PrimeFaces process/update and JSF…
  • What does a "Cannot find symbol" or "Cannot resolve…
  • Mock MQRFH2 header in JUnit Testing Error [MQRFH2…
  • Smart way to truncate long strings
  • What is the origin of foo and bar?
  • How to use java.net.URLConnection to fire and handle…
  • Android- Error:Execution failed for task…
  • How to parse JSON file with Spring
  • What are the new features in C++17?
  • JPA Hibernate Persistence exception…
  • Configure hibernate to connect to database via JNDI…
  • Callback functions in C++
  • How to paste yanked text into the Vim command line
  • Android Studio 4.2.1 NullPointer Exception on startup
  • What is the copy-and-swap idiom?
  • Could not install Gradle distribution from…
  • What does this symbol mean in JavaScript?
  • How do Mockito matchers work?
  • How to generate a random string of a fixed length in Go?
  • Fastest way to iterate over all the chars in a String
  • How can I use/create dynamic template to compile…
  • Vaadin Spring Boot - There was an exception while…
  • What is The Rule of Three?
  • commandButton/commandLink/ajax action/listener…
  • Why does C++ code for testing the Collatz conjecture…
  • Copy a variable's value into another
  • Eclipse fails to open .vue files in Web Page Editor
  • Round number to nearest integer
  • What is a stack trace, and how can I use it to debug…
  • Generate sequence of dates for given frequency as…
  • Getting Dropwizard Client And Jersey/HTTP I/O Error…
  • Get the name of an object's type
  • Launching Spring application Address already in use
  • ClassNotFoundException thrown
  • How do I print my Java object without getting…
  • Vue&TypeScript: how to avoid error TS2345 when…
  • What are the nuances of scope prototypal /…
  • Reduce vs Collect method on Parallel Streams vs…
  • How can I find the product GUID of an installed MSI setup?
  • How do I return the response from an asynchronous call?
  • Error inflating class android.support.v7.widget.Toolbar?
  • What is null in Java?
  • What is the scope of variables in JavaScript?
  • Java string to date conversion
  • How to select and view database with specific value?
  • "Non-resolvable parent POM: Could not transfer…
  • java.lang.RuntimeException: Unable to instantiate…
  • String is immutable. What exactly is the meaning?
  • How to handle initializing and rendering subviews in…
  • Dynamically allocating an array of objects
  • Swift: print() vs println() vs NSLog()
  • How to obtain the start time and end time of a day?

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

Rename column SQL Server 2008

Next Post:

What is the difference between a process and a thread?

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

.net ajax android angular arrays aurelia backbone.js bash c++ css dataframe ember-data ember.js excel git html ios java javascript jquery json laravel linux list mysql next.js node.js pandas php polymer polymer-1.0 python python-3.x r reactjs regex sql sql-server string svelte typescript vue-component vue.js vuejs2 vuetify.js

  • you shouldn’t need to use z-index
  • No column in target database, but getting “The schema update is terminating because data loss might occur”
  • Angular – expected call-signature: ‘changePassword’ to have a typedeftslint(typedef)
  • trying to implement NativeAdFactory imports deprecated method by default in flutter java project
  • What should I use to get an attribute out of my foreign table in Laravel?
© 2022 Fix Code Error