How to create a copy of my data type created in Java?

If I have a class:

public class MyType  
{  
    private List<Integer> data;  
    private boolean someFlag;

    public MyType(List<Integer> myData, boolean myFlag)
    {
        this.data = myData;
        this.myFlag = someFlag; 
    } 
}

Now, if I create an instance of MyType, how do I make a deep copy of it? I do not want the new object to point to the old link, but a completely new instance.

Is this the case when I have to implement the Cloneable interface, or is it used for small copies?

I can't just do:

MyType instance1 = new MyType(someData, false);  
MyType instance2 = new MyType(instance1.getData(), instance1.getFlag());

I'm worried about new instances of MyType pointing to the same link for their "data" variable. Therefore, I need to fully copy it.

So, if I have an existing object:

MyType someVar = new MyType(someList, false);

// Now, I want a copy of someVar, not another variable pointing to the same reference.

Can someone point me in the right direction?

+3
source share
5 answers

-: : myFlag someFlag?

Cloneable , :

public class MyType {

   private boolean myFlag;
   private List<Integer> myList;

   public MyType(MyType myInstance) {
      myFlag = myInstance.myFlag;
      myList = new ArrayList<Integer>(myInstance.myList);  
   }
}

Collections. Cloneable . , " Java" ( , . 61), Cloneable/clone.

  • .

, !

+7

Cloneable . (.. ), -:

List newData = new ArrayList(data)

, , . Integer s, . , .


, :

, java.

- Serializable .

+6

Cloneable. , " ". , , (== )

, . , int, long .., , .

, .

, .clone(). ( ) , , Cloneable , .

JavaDoc (Object.clone()) Clonable :

x.clone() != x && x.clone().getClass() == x.getClass() && x.clone().equals(x)

, ,

+1

MyType Cloneable. someVar.clone()

0

ICloneable

-1

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


All Articles