Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

adding elements of another arraylist by recursion-java

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?


1 Answers

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).

like image 121
RealSkeptic Avatar answered Jul 25 '26 19:07

RealSkeptic