简体   繁体   English

JAVA分配和运算符

[英]JAVA Assignment & Operators

the code below is printing out 15 15 , however I was expecting it to print out 12 15 . 下面的代码打印出15 15 ,但是我期望它打印出12 15 It seems like the fix method is updating a1 so that it contains 3,7,5 as opposed to 3,4,5. 似乎fix方法正在更新a1,使其包含3,7,5而不是3,4,5。 Anyone know why this is the case? 有人知道为什么会这样吗?

class PassA 
{
    public static void main(String [] args) 
{
    PassA p = new PassA();
    p.start();
}

void start() 
{
    long [] a1 = {3,4,5};
    long [] a2 = fix(a1);
    System.out.print(a1[0] + a1[1] + a1[2] + " ");
    System.out.println(a2[0] + a2[1] + a2[2]);
}

long [] fix(long [] a3) 
{
    a3[1] = 7;
    return a3;
}
}

Take a look at following 看看以下

 long[] fix(long[] a3) { // a3=a1 and a1= {3,4,5}
    a3[1] = 7; // a3[1]=7 means a1[1] will become 7(a1[1]=7), now a1={3,7,5}
    return a3;// return a1
}

This would achieve your target 12 15 这将实现您的目标12 15

long [] fix(long [] a3) 
{
    return new long[]{a3[0], 7, a3[2]};
}

Because otherwise, you pass a1 (named as a3), modify an element, which subsequently changes it in a1. 因为否则,您传递a1(命名为a3),则修改一个元素,然后在a1中对其进行更改。 So now a1 is changed. 因此,现在a1已更改。 Later on you return a1 and set it to a2.. So a2 and a1 are pointing to the same array {3,7,5} 稍后返回a1并将其设置为a2。因此a2和a1指向相同的数组{3,7,5}

You are passing the array by reference, thats why in the fix() method, the original array gets modified. 您正在通过引用传递数组,这就是为什么在fix()方法中,原始数组被修改的原因。 You can pass a copy to the method using 您可以使用以下方式将副本传递给方法

long [] a2 = fix( Arrays.copyOf(a1, a1.length));.

OK, technically, you are passing the array by value, but the value is the reference. 好的,从技术上讲,您是按值传递数组,但该值引用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM