-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 ?

tlq
  • 887
  • 4
  • 10
  • 21
  • Did you take a look at http://stackoverflow.com/questions/3291830/deep-copy-and-arraylist-java – hemanth Feb 02 '14 at 23:35
  • you didn't show any work which is bad – djechlin Feb 02 '14 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.. – tlq Feb 02 '14 at 23:40

1 Answers1

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?

Gábor Bakos
  • 8,982
  • 52
  • 35
  • 52
  • 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? – tlq Feb 03 '14 at 00:21
  • "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.) – Gábor Bakos Feb 03 '14 at 09:12