用Java传递参数 [英] Parameter passing in Java

查看:114
本文介绍了用Java传递参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道Java总是按值传递,但我不明白为什么会这样:

I know that Java is always pass-by-value, but I do not understand why this works:

public static void swap(int[] arr, int i, int j)
{
    int tmp = arr[i];
    arr[i] = arr[j];
    arr[j] = tmp;
}
public static void main(String[] args)
{
    int[] arr = {3, 4, 5, 6};
    swap(arr, 1, 3);
    // arr becomes {3, 6, 5, 4}
}

这不起作用:

public static void swap(int[] arr, int[] arr2)
{
    int[] tmp = arr;
    arr = arr2;
    arr2 = tmp;
}
public static void main(String[] args)
{
   int[] arr = {3, 4, 5, 6};
   int[] arr2 = {1, 2, 5, 6};
   swap(arr, arr2);
}

为什么?

推荐答案

在第二种方法中,您尝试交换引用,这些引用无效,因为引用本身是按值传递的。

In the second method, you are trying to swap references, which will not work because the references themselves are pass-by-value.

第一种方法正常工作,因为它改变了数组引用的对象(这是可变的),它不会改变引用本身。

The first method works correctly because it changes the object referenced by the array (which is mutable), it does not change the reference itself.

签出此博客文章,详细了解了传值和传递参考之间的差异。

Check out this blog post for more details on the differences between pass-by-value and pass-by-reference.

这篇关于用Java传递参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆