且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何正确返回ArrayList< Object>没有重复值的递归方法?

更新时间:2023-11-05 14:01:40

您想知道为什么它可以很好地打印,而返回的列表似乎在每个位置都有完全相同的数组。

这是因为它是完全相同的数组(相同的引用到同一对象)。由于在您的解决方案中仅使用一个数组,因此在调用 allResults.add(result)时,会将引用添加到列表中的唯一数组。然后,当您寻找其他组合时,请继续对其进行修改。这就是为什么列表仅包含找到的最后一个组合的原因。

You are wondering why it prints it fine while the returned list seems to have the exact same array at each position.
That's because it's the exact same array (same reference to the same object). Since in your solution you are using only one array, when you call allResults.add(result), you add the reference to your only array in the list. Then you keep modifying it when you look for the other combinations. That's why your list only contains the last combination found.

解决方案是,每次找到组合时,通过添加当前数组的副本来添加一个新数组到您的清单。只需替换

The solution to this is to add a new array each time you find a combination by adding a copy of your current array to your list. Simply replace

allResults.add(result);

通过

allResults.add(Arrays.copyOf(result, result.length));

这样,列表中的每个元素都指向一个不同的数组。

That way, every element of your list points to a different array.