'ArrayList<Integer> will only keep one set of parameters. the rest is not being updated
I'm confused as to why the variable answer will only output one set of answer. I have a recur function that basically counts from i to size. it will then return the arraylist of the counts. then increment i and repeat. but when I output to the console I get:
[1, 2, 3, 4, 5, 6, 7]
[]
[]
[]
[]
I was expecting something like this:
[1, 2, 3, 4, 5, 6, 7]
[2, 3, 4, 5, 6, 7]
[3, 4, 5, 6, 7]
......
public static ArrayList<Integer> practice(ArrayList<Integer> x, ArrayList<ArrayList<Integer>> y){
int inputSize = x.size();
ArrayList<Integer> answer = new ArrayList<Integer>();
for(int i = 0; i < inputSize; i++){
answer = recur(x, y, i);
System.out.println(answer);
}
public static ArrayList<Integer> recur(ArrayList<Integer> x1, ArrayList<ArrayList<Integer>> y1, int index){
ArrayList<Integer> ans = new ArrayList<Integer>();
for(int i = index; i < x1.size(); i++){
ans.add(i);
}
return ans;
}
Do I have to deallocate answer memory after the println?
Solution 1:[1]
I believe it's because you have your indices for the iterators wrong.
If you look closer (or log the variables) you'll see that in the recur
iterator i == index
always.
It's iterating 7 times, each time overwriting answer
with an ArrayList
that is growing with index
.
Only the first one printed correctly because you are setting that maxed out i
as index
of recur
where it becomes your starting index, and your ending index is the same size as the input array.
After the first iteration there is nothing to iterate on, so empty array.
If you want to use recursion you need to call the same method from itself and fix your indices.
public static ArrayList<Integer> practice(int start, int end){
ArrayList<Integer> answer = new ArrayList<Integer>();
for(int i = start; i < end; i++){
answer.add(i)
System.out.println(answer);
}
practice(start++, end);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |