如果Java是按值传递的,那么这个交换方法如何工作?

时间:2013-11-12 20:11:34

标签: java

好的,所以我理解Java是按值传递的(包括对于References,它通过引用的VALUE传递Object - 即地址)。

如果是这样,为什么swap(int[] array)方法 - 传递基元数组 - 工作?

public class TestArraySwap {

    public static void swap(int a, int b) {
        int temp =b;
        b=a;
        a=temp;
    }

    public static void swap(int[]a) {
        int temp = a[1];
        a[1]=a[0];
        a[0]=temp;
    }

    public static void main(String[] args) {
        //Test Primitive swap
        int a=1;
        int b=2;
        System.out.println("a="+a +" b="+b);
        swap(a,b);
        System.out.println("a="+a +" b="+b);

        //Test array swap
        int[] array = new int[2];
        array[0]=1;
        array[1]=2;
        System.out.println("a[0]="+array[0] +" a[1]="+array[1]);
        swap(array);
        System.out.println("a[0]="+array[0] +" a[1]="+array[1]);
    }
}

输出

a=1 b=2
a=1 b=2
a[0]=1 a[1]=2
a[0]=2 a[1]=1

第二次交换有效 - 我希望不会,但也许我错过了什么?

5 个答案:

答案 0 :(得分:3)

main方法引用了一个数组:

R1 ------> [1, 2]

然后调用swap()方法。因此,swap()方法创建并使用了对同一数组的引用的副本:

 R1 -----> [1, 2]
             ^
             |
 R2 ---------|

然后swap()方法更改数组的内容:

 R1 -----> [2, 1]
             ^
             |
 R2 ---------|

它又回来了。 R1仍引用相同的数组,其内容已更改。

答案 1 :(得分:0)

交换有效,因为您将数组的地址(引用)传递给方法。然后该方法对该数组进行操作 - 与另一个方法引用的相同。

我真的不喜欢这句话,“Java是值得传递的。”我认为这真的令人困惑。

<小时/>

 public void methodA(){
     int[] values = {1,2}; 
    // MethodA stack frame has a register that contains a 
    //   memory address (let's say it's 0x1F) that points to a contiguous section of 
    //   memory sized for an integerarray of size 2. 
     methodB(values); // Pass the **memory address** (aka REFERENCE) not the register address
     System.out.println(values[0]); // Prints "100"
 } 

 public void methodB(int[] ints){
     // MethodB stack frame now has a register with the memory address (0x1F)
     //    of 'ints' which is the same address that MethodA stack frame has.
     //    The same REFERENCE
     ints[0] = 100; // Alter the value in mem of 0x1F+0
     ints = new int[2]; // The local register overwrites the memory address of 
                        // the REFERENCE value that was there with 
                        // a new memory address -- say 0x5A
                        // since it's not storing it in the same register 
                        // as MethodA, MethodA will not reflect this.


 }

答案 2 :(得分:0)

经过一番搜索,我发现了这个答案 Array seems to be getting passed by reference in Java, how is this possible?

当然还有Java规范本身

  

在Java编程语言中,数组是对象

答案 3 :(得分:0)

Java中的所有内容都按值传递(通过复制)。

swap(int[] a)有效,因为它仅传递(复制)数组开头的地址。之后它会直接修改该地址(a[0])和下一个(a[1])下的记忆

swap(int a, int b)不起作用,因为它会修改整数的副本。

答案 4 :(得分:0)

Java中的引用指向堆中的对象。 Java中的数组总是在堆中分配。所以Java中的数组就像普通对象

Java中对象的引用存储在堆栈中,就像原始变量(intlong)一样,它是存储在变量中的内存地址。因此,当他们说对象按值传递时,字面意思是将地址值复制到方法参数中。

对我而言,这一直是令人困惑,因为虽然我确实理解了这个过程,但我不记得它是如何正确地命名为

  • Java中没有引用
  • 当我听到“值”这个词应用于某个对象时,我总是被卡住了