0

I need to create several new objects from an ArrayList. Suppose my list is:

ArrayList<InvVoucher> list = .....;
int index = 0;
InvVoucher vch1 = list.get(index);
InvVoucher vch2 = list.get(index);
InvVoucher vch3 = list.get(index);

Here vch1, vch2 and vch3 are holding the same object reference. How can I make all of them independent? How can I get three different copy of InvVoucher?

Pranjal Choladhara
  • 845
  • 2
  • 14
  • 35
  • 1
    Use the class' constructor to create new instances. – SLaks Aug 13 '19 at 16:41
  • If InvVoucher has a copy constructor, you can make a new instance with `InvVoucher vch1 = new InvVoucher(list.get(index)):` – Jamie Aug 13 '19 at 16:43
  • Your question is: how do you create a copy of an object? It is not important if the original object came out of an ArrayList. You could address this by either creating a new `InvVoucher` constructor which takes one argument – another `InvVoucher` instance – and copies values from it. Or you could create a `clone()` method on `InvVoucher` and use that. – Kaan Aug 13 '19 at 17:24

1 Answers1

0

One way would be to implement a copy constructor in IntVoucher as suggested in the comments.

public class IntVoucher {
    public IntVoucher(IntVoucher original) {
        this.field1 = new Field1(original.field1);
        ...
    }
    private Field1 field1;
    ...
}

That way you can do

IntVoucher vch1 = new IntVoucher(list.get(index));

Another possibility is overriding the clone method in IntVoucher and having it implement the java.lang.Cloneable interface.

public class IntVoucher implements Cloneable {
    // note: change from protected to public if needed
    protected IntVoucher clone() {
       IntVoucher clone = new IntVoucher();
       clone.field1 = new Field1(this.field1);
       ...
       return clone;
    }
    private Field1 field1;
    ...
}

Read more on shallow / deep copying in Java. There are lots of complete examples if this isn't enough.

geco17
  • 5,152
  • 3
  • 21
  • 38
  • That is not how you implement `clone()` in Java, see [`Cloneable`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Cloneable.html) – Mark Rotteveel Aug 13 '19 at 18:39