Home > database >  How to duplicate a list to another list (deep copy) without using clone()?
How to duplicate a list to another list (deep copy) without using clone()?

Time:05-30

I want to duplicate the data from currentList to newList. Is it possible to duplicate it without adding the clone() method inside the Object class?

I have tried a couple of codes that i found:

1.

List<InvoiceDetail> newList= new ArrayList<>();
newList.addAll(currentList);
newList = currentList.stream().collect(Collectors.toList());

But as I was processing the data in the newList, some of the data in currenList will change too. If possible, I want to retain the data in currentList.

CodePudding user response:

If I understand the problem correctly, you want a new list to be fulfilled with the copies of InvoiceDetail objects, right? So, in my understanding, the problem is not how you operate with lists, but rather how InvoiceDetail is implemented. I would probably go with the copy constructor in the InvoiceDetail class. Like that:

class InvoiceDetail {
    
    // your existing constructors

    public InvoiceDetail(InvoiceDetail source) {
        // the logic of copying the invoice data
        // like this.someField = source.someField; etc.
    }

    // other methods
}

Then you could do something like that:

newList = currentList.stream().map(InvoiceDetail::new).collect(Collectors.toList());

Can that be a solution to your problem?

Alternative solution: if you do not want to bother with changing InvoiceDetail class, you may (if possible) create a clone object on the fly like that:

newList = currentList.stream().map(
    source -> {
        final InvoiceDetail target = new InvoiceDetail();
        // copy the data like target.setSomeField(source.getSomeField());
        return target;
    }
).collect(Collectors.toList());

CodePudding user response:

If I understand your problem, you need to retain currenList as is as you process data in newList. Then in that case, I think you might need have your currenList as Unmodifiable Lists.

You can use any List.of implementation for creating Unmodifiable Lists. After that, you can simply copy element to new list & verify if they are deep equal:

List<InvoiceDetail> currnList = *Unmodifiable Lists* ;
List<InvoiceDetail> newList= new ArrayList<>();
newList.addAll(currentList);

System.out.println(Arrays.deepEquals(currnList.toArray(),newList.toArray())); //  returns true if they are deep equal.
  • Related