Adding elements of another arraylist recursive-java
Here is a method that should just create a new ArrayList copying all the elements of the ArrayList parameter arrlist, which I think I did 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 would like to write this exact method using recursion only without loops. Here's 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);
}
Also, it doesn't work. Any suggestions or hints?
The problem is you are creating a new one ArrayList
in every recursion. And you are not going back anywhere.
What you need to do is in the helper method also pass the target ArrayList
as a parameter and add to it instead of a new one.
(And of course, don't forget to come back when you're done.)
source to share
See below for basic recursive fibonacci function:
public int fib(int n) {
if(n <= 1) {
return n;
} else {
return fib(n - 1) + fib(n - 2);
}
}
It works like a recursive function because it has a base case, a path that the function will take to return a result that is not another call to itself. To complete the recursive call, you need the base register if the condition is met and return the results.
source to share
Try the following:
private void copy(ArrayList<T> src, ArrayList<T> src_copy, int n) {
if (n>=0){
src_copy.add(src.get(n));
copy(src,src_copy, n-1);
}
}
Then use it like below:
ArrayList<T> src = ... ; //your arrayList
ArrayList<T> src_copy = new ArrayList<T>();
if (src != null && src.size() > 0) {
copy(src, src_copy, src.size()-1);
}
source to share
I don't know what kind of error you are getting. but I think it should work.
public ArrayList<T> copy(ArrayList<T> arrlist) {
ArrayList<T> um = new ArrayList<T>();
return copy(arrlist, um, 0);
}
private ArrayList<T> copy(ArrayList<T> arrlist, ArrayList<T> um, int n) {
if (n < arrlist.size())
um.add(arrlist.get(n));
else
return um;
return copy(arrlist, um, n+1);
}
source to share