adding elements of another arraylist by recursion-java

10,220

Solution 1

The problem is that you are creating a new ArrayList in every recursion. And you are not returning it anywhere.

What you should do is, in the helper method, also pass the target ArrayList as a parameter, and add to it rather than a new one.

(And of course, don't forget to return when you're done).

Solution 2

You are allocating (ArrayList um=new ArrayList();) array list in every recursive call. Also I can not see when the recursive function will stop to call itself

Share:
10,220
Admin
Author by

Admin

Updated on June 06, 2022

Comments

  • Admin
    Admin almost 2 years

    Here is a method that is supposed to simply create a new ArrayList copying all the elements of parameter ArrayList arrlist, which I think I've done correctly.

    public ArrayList<T> copy (ArrayList<T> arrlist) {
            ArrayList<T> um=new ArrayList<T>();
            for (int i=0;i<arrlist.size();i++)
                um.add(arrlist.get(i));
            return um;
    

    However, I'd like to write this exact same method using recursion only with no loops. Here is what I wrote. The copy method uses a recursive helper method.

    public ArrayList<T> copy(ArrayList<T> arrlist) {
        return copy(arrlist,0); 
    }
    
    private ArrayList<T> copy(ArrayList<T> arrlist, int n) {
        ArrayList<T> um=new ArrayList<T>();
        if (n<arrlist.size())
            um.add(list.get(n));
        return copy(list,n+1); 
    }
    

    Except this does not work. Any suggestions or hints?