-3

I had to return ArrayList of ArrayList<Integer> as it was predefined.
I was trying this code( for pascal triangle of n lines):

ArrayList<ArrayList<Integer>> a = new ArrayList<ArrayList<Integer>>();
ArrayList<Integer> b = new ArrayList<Integer>();
for(int i=1;i<=n;i++){
    int c=1;
    //ArrayList<Integer> b = new ArrayList<Integer>(); I declared
    //the arraylist here to solve the problem
    // Place 1: b.clear()
    for(int j=1;j<=i;j++){
        b.add(c);
        c=(c*(i-j))/j;
    }
    a.add(b);
    // Place 2: b.clear();
}
return a;

Expected output: n=4 : [1 ] [1 1 ] [1 2 1 ] [1 3 3 1 ]
I wanted to know why i was not getting the desired output when i placed clear functions at:
Place 1 output: [1 3 3 1 ] [1 3 3 1 ] [1 3 3 1 ] [1 3 3 1 ] (Only the last row)
Place 2: [ ] [ ] [ ] [ ] (no output)
The same was the case with removeAll().

abdulwasey20
  • 747
  • 8
  • 21
  • 1
    You have only one `ArrayList`, with multiple references to it. One reference is `b`. The rest are inside `a`. – khelwood Mar 14 '19 at 19:00
  • See: [Why does my ArrayList contain N copies of the last item added to the list?](https://stackoverflow.com/q/19843506/5221149) – Andreas Mar 14 '19 at 19:02

2 Answers2

1

It is the same reference of the ArrayList even if you have cleared it. So, modifying one copy will modify all the others also. You should really be creating a new instance of ArrayList instead of clearing it. Modified code below:

ArrayList<ArrayList<Integer>> a = new ArrayList<ArrayList<Integer>>();
ArrayList<Integer> b;
for (int i = 1; i <= n; i++) {
    int c = 1;
    // ArrayList<Integer> b = new ArrayList<Integer>(); I declared
    // the arraylist here to solve the problem
    b = new ArrayList<Integer>(); // NEW INSTANCE INSTEAD OF CLEARING IT
    for (int j = 1; j <= i; j++) {
        b.add(c);
        c = (c * (i - j)) / j;
    }
    a.add(b);
}
return a;
Prasann
  • 1,263
  • 2
  • 11
  • 18
1

Not sure whether you understood the problem Since array b is declared outside for loop , after each iteration on the outer loop same object is used and continuing with old values.

To get desired out put, make new b object within outer loop

instead of

ArrayList<Integer> b = new ArrayList<Integer>();
for(int i=1;i<=n;i++){

try this

ArrayList<Integer> b = null;
for(int i=1;i<=n;i++){
b = new ArrayList<Integer>();
WhyJava
  • 110
  • 3
  • 10