JAL
JAL

Reputation: 42449

Copying a 2D String ArrayList

This seems really trivial, but I'm having trouble copying a 2D String ArrayList into an entire new 2D String ArrayList data structure.

public static ArrayList<ArrayList<String>> copy(ArrayList<ArrayList<String>> input) {

    ArrayList<ArrayList<String>> copy = new ArrayList<ArrayList<String>>();

    for(int i = 0; i < input.size(); i++) {
        ArrayList<String> line = input.get(i);  // Issue here?
        for(int j = 0; j < input.get(i).size(); j++) {
            line.set(j, input.get(i).get(j));
        }
    }
    return copy;
}

I'm not looking to make a shallow copy, I'm trying to iterate over an entire ArrayList and copy it into a new one. I feel like I'm not initializing the rows correctly with my line ArrayList, but I thought the whole point of the ArrayList data structure was that data could be added to it without initializing the size?

It appears the first line is being copied correctly, but I'm indexing out of bounds when I try to add a subsequent line.

Upvotes: 3

Views: 2113

Answers (2)

vallentin
vallentin

Reputation: 26167

You're forgetting to create the ArrayList inside the ArrayList itself.

public static ArrayList<ArrayList<String>> copy(ArrayList<ArrayList<String>> input) {

    ArrayList<ArrayList<String>> copy = new ArrayList<ArrayList<String>>();

    for(int i = 0; i < input.size(); i++) {
        ArrayList<String> line = new ArrayList<String>();

        for(int j = 0; j < input.get(i).size(); j++) {
            line.add(input.get(i).get(j));
        }

        copy.add(line);
    }
    return copy;
}

Upvotes: 3

Iłya Bursov
Iłya Bursov

Reputation: 24146

public static ArrayList<ArrayList<String>> copy(ArrayList<ArrayList<String>> input) {
    ArrayList<ArrayList<String>> copy = new ArrayList<ArrayList<String>>(input.size());
    for(int i = 0; i < input.size(); i++) {
        ArrayList<String> line = input.get(i);
        copy.set(i, new ArrayList<String>(line.size())); // add internal array initialization
        for(int j = 0; j < line.size(); j++) {
            copy.get(i).set(j, line.get(j)); // actually copy value into new array
        }
    }
    return copy;
}

Upvotes: 2

Related Questions