java - ArrayList of ArrayLists in Recursion -


i've been working on larger project, , ran problem have replicated here in simpler fashion. i'm trying add arraylist of integers arraylist. problem every arraylist add larger arraylist gets updated if 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) {            (arraylist<integer> : test1) {             (integer : a) {                 system.out.print(i + "  ");             }             system.out.println();         }         return;     }            testrecurse(n - 1);      }  public static void main(string[] args) {             testrecurse(10); } } 

the output 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 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 explain me happening here? , perhaps suggest work around such situation.

you adding exact same object test arraylist on , on again. why getting modified together.

everytime want add it, need create new arraylist<integer>() before add it.

you can try replacing

test1.add(test); 

with

test = new arraylist<integer>(test); test1.add(test); 

this makes copy of current test , adds list.

this still mean integer elements contained in arraylist exhibit same bug, since shallow copy, since not modifying them, ok case.


Comments

Popular posts from this blog

css - Which browser returns the correct result for getBoundingClientRect of an SVG element? -

gcc - Calling fftR4() in c from assembly -

Function that returns a formatted array in VBA -