Java 为什么我的交换功能有效?
据我所知,Java是按值传递的,也就是说,当我使用基本类型时,我不能交换它们(如果我使用对象,这是可能的)。我写了一个程序来记录整数数组的所有排列。为此,我使用了一个Java 为什么我的交换功能有效?,java,arrays,pass-by-value,primitive-types,Java,Arrays,Pass By Value,Primitive Types,据我所知,Java是按值传递的,也就是说,当我使用基本类型时,我不能交换它们(如果我使用对象,这是可能的)。我写了一个程序来记录整数数组的所有排列。为此,我使用了一个swap函数,该函数将两个位置作为参数数组,并在这些位置交换数字。我的程序也能正常工作?!谁能解释一下为什么?代码如下: public class Solution { public List<List<Integer>> permute(int[] num) { if(num ==
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[]num){
如果(num==null | | num.length==0)
返回null;
List res=new ArrayList();
doPermute(num,0,res);
返回res;
}
公共静态void doPermute(int[]num,int k,List res){
如果(k==num.length){
res.add(convertArrayToList(num));
返回;
}
for(int i=k;i
Java是按值传递的。对象的值是引用地址。数组(即使是int[]
)也是一个对象。所以
public static void swap(int[] num, int i, int j){
int temp = num[i];
num[i] = num[j];
num[j] = temp;
}
数组
num
可在swap
中修改。如果查看,您会注意到这些方法采用了对象数组
,这将起作用,因为您正在传递正在更改的对象的引用,在您的示例中,int[]
。请注意,int[]
也是一个对象。如果您只是传递数组的值,然后尝试更改它,这是没有用的。考虑这个< /P>
//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
因为您有正在更改的可变数组对象的引用,所以不存在任何问题可能会重复您的交换方法。请注意它是如何不改变任何参数的。。。这里没有
i=…
或num=…
或j=…
…顺便说一句,交换对象引用就像交换原语类型值一样不可能,所以您的语句“如果我使用对象,那么它是可能的”是不正确的。不要将“修改对象”与“为变量指定新值”混为一谈。