0

I checked other answers but I could not find a proper answer to my question. I want to create a copy of my ArrayList<ArrayList>, since I need the original one somewhere else. I used the .clone() method in different ways:

public class WordChecker {

    private ArrayList<ArrayList> copyOfList = new ArrayList<ArrayList>();

    public WordChecker(ArrayList<ArrayList> list) {
        for (int i = 0; i < list.size(); i++)
            for (int j = 0; j < 7; j++)
                copyOfList = (ArrayList<ArrayList>) list.clone(); // without error
                // copyOfList = list.clone();cannot convert from Object to
                // ArrayList<ArrayList>
                // copyOfList = list.get(i).clone();cannot convert from Object to
                // ArrayList<ArrayList>
                // copyOfList = list.get(i).get(j).clone();
    }

but still my main ArrayList changes as I work on its copy. Could anybody tell me how I should get a deep copy in this case?

Answer: I put the copying mechanism in my class constructor:

private ArrayList<List> checkedTags = new ArrayList<List>();
public WordChecker(ArrayList<ArrayList> list)
  {
     for (ArrayList word: list) copyOfList.add((ArrayList) word.clone());

}

the only problem is that this is not applicable to copy from ArrayList which made me to go through a for loop use .get() method.I feel they are basically the same at the end.

msc87
  • 943
  • 3
  • 17
  • 39
  • 2
    Don't use clone(). Use the ArrayList constructor that takes another collection as argument. And you'll need to loop if you want a deep copy. – JB Nizet Mar 27 '14 at 10:32
  • Take a look here: http://stackoverflow.com/questions/715650/how-to-clone-arraylist-and-also-clone-its-contents – Robert Niestroj Mar 27 '14 at 10:33
  • I made a nested loop to reach to every item in the inner ArrayList. it throws the error mentioned in front of the code. I used this code: >> for (ArrayList word: list) copyOfList.add(word.clone())... too. but it cannot accept .add . – msc87 Mar 27 '14 at 11:02

1 Answers1

-1

You can simply use ArrayList(Collection c) constructor

public <T> ArrayList<ArrayList<T>> deepCopy(ArrayList<ArrayList<T>> source) {
    ArrayList<ArrayList<T>> dest = new ArrayList<ArrayList<T>>();
    for(ArrayList<T> innerList : source) {
        dest.add(new ArrayList<T>(innerList));
    }
    return dest;
}

Caution: As mentioned by @Tim B this does not deep copy the elements within ArrayList

sanbhat
  • 17,522
  • 6
  • 48
  • 64