ArrayList of ArrayLists in Recursion
I've been working on a larger project, and ran into a problem which I have
replicated here in a much simpler fashion. What I'm trying to do is to add
an ArrayList of Integers into another ArrayList. The problem is that every
ArrayList I add into the larger ArrayList gets updated as if they were all
the same.
public class RecursionTest {
static ArrayList<Integer> test = new ArrayList<Integer>();
static ArrayList<ArrayList<Integer>> test1 = new
ArrayList<ArrayList<Integer>>();
public static void testRecurse(int n) {
test.add(n);
if (n % 2 == 0) {
test1.add(test);
}
if (n == 0) {
for (ArrayList<Integer> a : test1) {
for (Integer i : a) {
System.out.print(i + " ");
}
System.out.println();
}
return;
}
testRecurse(n - 1);
}
public static void main(String[] args) {
testRecurse(10);
}
}
The output I get is:
10 9 8 7 6 5 4 3 2 1 0
10 9 8 7 6 5 4 3 2 1 0
10 9 8 7 6 5 4 3 2 1 0
10 9 8 7 6 5 4 3 2 1 0
10 9 8 7 6 5 4 3 2 1 0
10 9 8 7 6 5 4 3 2 1 0
When it should be:
10
10 9 8
10 9 8 7 6
10 9 8 7 6 5 4
10 9 8 7 6 5 4 3 2
10 9 8 7 6 5 4 3 2 1 0
Can someone explain to me what is happening here? And perhaps suggest a
work around for such a situation.
No comments:
Post a Comment