Dynamic
Dynamic

Reputation: 507

Recursive Function Not Adding Items to ArrayList in Java

I am trying to add an array of arrays to an ArrayList in Java. Only the last iteration of recursion is added to the ArrayList multiple times. I have the following Java class:

import java.util.ArrayList;

public class Test {
    ArrayList<int[][]> result;
    int[][] part;

    public Test() {
        result = new ArrayList<int[][]>();
        part = new int[2][2];
    }

    public void fill(int i) {
        if(i > 0) {
            part[0][0] = i;
            result.add(part);
            i--;
            fill(i);
        }
    }

    public static void main(String[] args) {
        Test test = new Test();
        test.fill(4);

        for(int l = 0; l < test.result.size() - 1; l++) {
            for(int i = 0; i < 2; i++) {
                for(int j = 0; j < 2; j++) {
                    System.out.print(test.result.get(l)[i][j] + " ");
                }
                System.out.println();
            }
            System.out.println("-----");
        }
    }
}

When I run it, I get the following result:

1 0 
0 0 
-----
1 0 
0 0 
-----
1 0 
0 0 
-----

Where I would expect:

3 0 
0 0 
-----
2 0 
0 0 
-----
1 0 
0 0 
-----

Upvotes: 2

Views: 338

Answers (2)

dan1st
dan1st

Reputation: 16348

The fill method takes the array, set it's value at [0][0] to i and adds it to the list.

Then, it takes the same array(actually a reference to that array), overwrites it's value at [0][0] to i and adds it to the list.

So, you've added the same array multiple times but you have overwritten the first value in it.

[Note]

The attributes of your Test class are package private. I recommand you to set the visibility to private if there is no reason to do anything else.

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726559

This is because you keep adding the same object part three times. The last update "sticks", while the prior ones get written over.

Moving array initialization into the body of your recursive method would fix this problem:

public void fill(int i) {
    if(i > 0) {
        int[][] part = new int[2][2];
        part[0][0] = i;
        result.add(part);
        i--;
        fill(i);
    }
}

Also remove the declaration of part from the Test class, because it is no longer in use.

Upvotes: 1

Related Questions