Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Empty list getting added in ArrayList

I am writing a recursive method to get all the subsequence of a list that has a particular sum.
But, when I add them to the resultList(ArrayList<ArrayList), I am getting an empty list in the output.

Can someone please suggest what am I doing wrong here?
Below is the code:

public class SubsequenceUsingRecursion {

    static List<ArrayList<Integer>> result = new ArrayList<>();
    public static void main(String[] args) {
        
        // Input
        int arr[]= {1,2,3};
        // Required Sum
        int sum=3;
        ArrayList<Integer> list = new ArrayList<>();
        
        getSubsequece(arr, 0, list,sum);

        System.out.println(result);
    }

    private static void getSubsequece(int[] arr, int i, ArrayList<Integer> list, int sum) {
        if(i>=arr.length)
        {
            int sums =list.stream().reduce(0,(a,b)->a+b);
            if(sums==sum) {
                System.out.println(list);
                result.add(list);
            }
            return;
        }
        list.add(arr[i]);       
         getSubsequece(arr, i+1, list,sum);
        list.remove(list.size()-1);
        getSubsequece(arr, i+1, list,sum);
        return;
    }

Attached Output:
line 1 and line 2 are System.out.println(list)
line 3: final result ArrayList (Showing empty with correct number of elements)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Console Output:

enter image description here

>Solution :

You keep working on the reference of the list that has been added via result.add(list) later after it already has been added, thus changing it. My recomendation is that you first compose all that must be inside in this list, then place it in the result list and then continue working on its copy (copy method), to avoid potential bugs like in this case.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading