I am trying to write a procedure do the deep copy of List<List<Integer>>, and I am doing like this:
public static List<List<Integer>> clone(final List<List<Integer>> src)
{
List<List<Integer>> dest = new ArrayList<List<Integer>>();
for( List<Integer> sublist : src) {
List<Integer> temp = new ArrayList<Integer>();
for(Integer val: sublist) {
temp.add(val);
}
dest.add(temp);
}
return dest ;
}
Is this a good way to do? Is it possible to get rid of the inner loop? The fact is that each of the inner sub-lists can grow to large lengths.
Is this a good way to do?
It's fine.
Is it possible to get rid of the inner loop?
Yes, you can use the ArrayList copy constructor:
for( List<Integer> sublist : src) {
dest.add(new ArrayList<>(sublist));
}
The fact is that each of the inner sub-lists can grow to large lengths.
The above will shorten the code, and it delegates to System.arraycopy, which will likely improve performance somewhat. It also avoids the repeated resize/copy when you fill an empty ArrayList. But there's fundamentally no way to avoid the O(n) time complexity of copying a list/array, if you truly need a deep copy. Since you don't explain why you need a deep copy, I'll have to take you at your word.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With