3

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.

13
  • 3
    If you want to do a deep copy, then there's nothing you can do about the size of the sub-lists - something will need to iterate over them at some point (unless you can build a copy-on-write mechanism). Commented Jun 19, 2017 at 22:02
  • Integer is immutable; anything you do to an Integer is lost unless you re-add it back into the list in its exact place. Why do you think you want a deep copy? Commented Jun 19, 2017 at 22:04
  • Off topic here. Try codereview.stackexchange.com. Commented Jun 19, 2017 at 22:05
  • 1
    @Makoto - I believe the OP is referring to memcpy only because in C it's generally faster than manually iterating and copying, not because memcpy has any semantic value. He/she is essentially asking "am I doing a deep copy as efficiently as possible?". Commented Jun 19, 2017 at 22:15
  • 1
    Using the copy constructor should indeed give you performance closer to memcpy. See my updated answer. Commented Jun 19, 2017 at 22:56

2 Answers 2

8

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.

Sign up to request clarification or add additional context in comments.

Comments

-2

You might be able to speed things up with some parallel approach, like using a Thread pool to split the work at first and merge the results together after everything is done.

I can't provide an example since I'm on my phone, but may try to look that way.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.