Is there a way to use recursion to populate arrays, without implementing method overloading? I want to build a method that takes only an int as argument, and returns an array. The only solution I have thought of is using method overloading; the function that takes int as argument builds the array and passes both the array and the int to the second function, which takes both the int and the array as arguments and implements the actual recursion.
Here is an example:
public static int[] recursiveBuilder(int depth, int[] anArray){
// Base case:
if (depth < 0){
return anArray;
}
// Recursion:
else{
anArray[depth] = depth;
depth--;
return recursiveBuilder(depth, anArray);
}
}
public static int[] recursiveBuilder(int depth){
return recursiveBuilder(depth, new int[depth + 1]);
}
If I declare the array in the recursive part of the overloading, the array would get initialized every time the recursion is called, so I used a second function to declare the array.
Is this approach considered good? Efficient? Is there a way to implement this dynamic in only one method?