How to clone an object in java

I want to create a list / array of an object with the same parent class, which I will then use it for reference. but I don’t know how to clone this object to create a new object.

here is an example

BigFoo a;
SmallFoo b;
ChickenFoo c;
List<Foo> foos;
foos.add(a);
foos.add(b);
foos.add(c);

Foo foo = foos.get(1).clone();

but in Java I did not find the clone function in the default function. I wonder how this is done?

+3
source share
3 answers

General suggestion: use the copy constructor. In fact, only the class itself knows how to create a clone on its own. No class can clone an instance of another class. The idea is this:

public class Foo {
  public List<Bar> bars = new ArrayList<Bar>();
  private String secret;

  // Copy constructor
  public Foo(Foo that) {
    // new List
    this.bars = new ArrayList<Bar>();

    // add a clone of each bar (as an example, if you need "deep cloning")
    for (Bar bar:that.bars) {
      this.bars.add(new Bar(bar));
    }

    // clone the secret value
    this.secret = new String(that.secret);
  }

  // ...

}

So, if we want to clone a foo, we just create a new one based on foo:

Foo clonedFoo = new Foo(foo);

This is the recommended way to clone an instance.


Copy constructor

.

 public ChildFoo extends Foo {

   private int key;

   public ChildFoo(ChildFoo that) {
     super(that);
     this.key = that.key;
   }
 }

foo , ChildFoo .

, . :

 Foo a = new Foo();
 ChildFoo b = new ChildFoo(a);  

ChildFoo:

 public ChildFoo(Foo that) {
     // call the copy constructor of Foo -> no problem
     super(that);

     // but how to initialize this.key? A Foo instance has no key value!
     // Maybe use a default value?
     this.key = 0;
 }

, b a, . , ( ) .

+4

- json mapper (Jackson Gson) , clone .

+1

Source: https://habr.com/ru/post/1793600/


All Articles