Вопрос

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.

Это было полезно?

Решение

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

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top