-1

i need a method that makes a deep copy..it takes as parameter ArrayList<Arraylist<Integer>>m and makes a deep copy to another ArrayList which collects also ArrayLists... Everything needs to be deep copied.But no loops only recursively...

Could someone help me how to do it ?

3
  • Did you take a look at stackoverflow.com/questions/3291830/… Commented Feb 2, 2014 at 23:35
  • you didn't show any work which is bad Commented Feb 2, 2014 at 23:37
  • well i can recursively make a deep copy of an arraylist..but , i dont know how to do since arraylist has arraylists inside..i cant use the arraylists copy constructor because it is a shallow copy.. Commented Feb 2, 2014 at 23:40

1 Answer 1

1

I think the following code like below satisfies your constraints and similar to what you want to achieve:

public ArrayList<ArrayList<Integer>> deepCopy(ArrayList<ArrayList<Integer>> list) {
    ArrayList<ArrayList<Integer>> ret = new ArrayList<ArrayList<Integer>>();
    deepCopy(list.iterator, ret);
    return ret;
}

private void deepCopy(Iterator<ArrayList<Integer>> it, ArrayList<ArrayList<Integer>> ret) {
    if (it.hasNext()) {
        ret.add(new ArrayList(it.next()));
        deepCopy(it, ret);
    }
}

It just visits the list and creates new lists recursively.

With Integers there are no interesting uses cases though... Is this homework?

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

2 Comments

it does actually copy all integer values into one arraylist inside of arraylist.the other ones created but inside of them empty..Do i see something wrong here?
"but inside of them empty", sorry, I do not understand this part of your statement. The copy constructor creates a new array with the values. It is true, that the Integer instances will remain the same. Although the idea I presented above would work there too. (Although I would use Integer.valueOf(...) instead of new Integer(...), so probably there would be not much difference.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.