据我所知,Java 是按值传递的,即当我使用原始类型时,我无法交换它们(如果我使用对象,则这是可能的)。我编写了一个程序来写下整数数组的所有排列。为此,我使用 swap
函数,该函数将数组、两个位置作为参数,并交换这些位置中的数字。我的程序工作?!有人可以解释一下为什么吗?下面是代码:
public class Solution {
public List<List<Integer>> permute(int[] num) {
if(num == null || num.length == 0)
return null;
List<List<Integer>> res = new ArrayList<List<Integer>>();
doPermute(num, 0, res);
return res;
}
public static void doPermute(int[] num, int k, List<List<Integer>> res){
if(k == num.length){
res.add(convertArrayToList(num));
return;
}
for(int i = k; i < num.length; i++){
swap(num, i, k);
doPermute(num, k+1, res);
swap(num, k, i);
}
}
public static List<Integer> convertArrayToList(int[] num){
List<Integer> res = new ArrayList<Integer>();
for(int i = 0; i < num.length; i++){
res.add(num[i]);
}
return res;
}
public static void swap(int[] num, int i, int j){
int temp = num[i];
num[i] = num[j];
num[j] = temp;
}
}
最佳答案
这将起作用,因为您正在传递要更改的对象的引用,在您的情况下 int[]
。请注意,int[]
也是一个对象。如果你只是传递数组的值,然后尝试更改它,那是没有用的。考虑一下
//Of little use ,the caller Object is not affected in any way
public static void swap(int i, int j){
int temp = i
i = j;
j = i;
}
swap(num[k], num[i]); //invoking of swap method,caller Object reference is not passed,just assignment of parameter value takes place
由于您拥有要更改的可变数组对象的引用,所以没有问题
关于java - 为什么我的交换功能有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25514964/