java - 为什么我的交换功能有效?

标签 java arrays pass-by-value primitive-types

据我所知,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/

相关文章:

objective-c - ios - 将数据传递给另一个方法 - 相同的 viewController

java - 如何使用正则表达式检查字符串是否仅包含特定字符

javascript - 对象实例的数组长度大于提供的参数

c++ - C++ 中的矩形二维字符数组

go - "value semantics’ "和 "pointer semantics"在 Go 中是什么意思?

c++ - 哪个更快?按引用传递与按值传递 C++

java - ListView内存问题

java - 按钮是_armed_是什么意思?

java - 如何在 Lombok 中调用 super 构造函数

java - 对对象数组使用 Arrays.binarySearch 并在对象中查找字符串