How do I copy an object in Java

De openkb
Aller à : Navigation, rechercher

Sommaire

Questions

Consider the below code:

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 I want to change dum without affecting the dumtwo . But the above code 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 ?

Answers

Create a copy constructor:

class DummyBean {
  private String dummy;

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

http://books.google.com/books?id=ka2VUBqHiWkC&pg=PA55&lpg=PA55&dq=effective+java+clone&source=bl&ots=yXGhLnv4O4&sig=zvEip5tp5KGgwqO1sCWgtGyJ1Ns&hl=en&ei=CYANSqygK8jktgfM-JGcCA&sa=X&oi=book_result&ct=result&resnum=3#PPA54,M1 http://books.google.com/books?id=ka2VUBqHiWkC&pg=PA55&lpg=PA55&dq=effective+java+clone&source=bl&ots=yXGhLnv4O4&sig=zvEip5tp5KGgwqO1sCWgtGyJ1Ns&hl=en&ei=CYANSqygK8jktgfM-JGcCA&sa=X&oi=book_result&ct=result&resnum=3#PPA54,M1

Source

License : cc by-sa 3.0

http://stackoverflow.com/questions/869033/how-do-i-copy-an-object-in-java

Related

Outils personnels
Espaces de noms

Variantes
Actions
Navigation
Outils