Chl*_*rty 2 java recursion combinations add arraylist
我班上有以下代码:
public static ArrayList<String[]> allCombos;
public static void main(String[] args){
allCombos = new ArrayList<String[]>();
String[] arr = {"A","B","C","D","E","F"};
combinations(arr, 3, 0, new String[3]);
}
static void combinations(String[] arr, int len, int startPosition, String[] result){
if (len == 0){
allCombos.add(result); // this is where the problem seems to be
return;
}
for (int i = startPosition; i <= arr.length-len; i++){
result[result.length - len] = arr[i];
combinations(arr, len-1, i+1, result);
}
}
Run Code Online (Sandbox Code Playgroud)
出于某种原因,每次allCombos.add(result)调用时combinations(),该方法似乎将整个数组中的每个元素设置为结果的当前值,从而超过前一次迭代combinations()设置最近添加的allCombosas的值.如果allCombos是a ,也会发生同样的事情Vector.
任何人都可以告诉我为什么会发生这种情况以及如何解决这个问题?
您多次添加相同的result数组ArrayList,因此您ArrayList包含对同一数组对象的多个引用.
您应该创建数组的副本,以便ArrayList包含不同的数组.
更改
allCombos.add(result);
Run Code Online (Sandbox Code Playgroud)
至
allCombos.add(Arrays.copyOf(result,result.length));
Run Code Online (Sandbox Code Playgroud)
进行更改后,打印您的allCombos List给出:
[A, B, C]
[A, B, D]
[A, B, E]
[A, B, F]
[A, C, D]
[A, C, E]
[A, C, F]
[A, D, E]
[A, D, F]
[A, E, F]
[B, C, D]
[B, C, E]
[B, C, F]
[B, D, E]
[B, D, F]
[B, E, F]
[C, D, E]
[C, D, F]
[C, E, F]
[D, E, F]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
257 次 |
| 最近记录: |