简体   繁体   English

变量在执行操作后不改变其值

[英]Variable not changing its value after operation performed

I have the following piece of code:我有以下代码:

 int[] a = {1,2,3,4};
 int temp = a[0];
 a[0] = 2;
 System.out.println(temp); //1

Why is it that the variable temp does not change its value to 2 after I execute the command on line 3?为什么我在第 3 行执行命令后变量 temp 的值没有更改为 2?

In Java, everything is assigned by value.在 Java 中,一切都是按值分配的。

int[] a = {1,2,3,4};

In the above line, you create an array that stores 4 numbers.在上面的行中,您创建了一个存储 4 个数字的数组。

int temp = a[0];

Here, you assign the value stored in a[0] to the variable temp .在这里,您将存储在a[0]中的值分配给变量temp

a[0] = 2;

Here you reassigned the value in a[0] , so there is something new that a[0] references to.在这里,您重新分配了a[0]中的值,因此a[0]引用了一些新内容。

System.out.println(temp);

Prints the value stored in the temp variable.打印存储在temp变量中的值。


The variables in Java aren't pointers. Java 中的变量不是指针。 They store values.他们存储价值。 Those values are either the value itself (for primitives; eg 1,100, false) or the reference to an object itself.这些值要么是值本身(对于原语;例如 1,100,false),要么是对 object 本身的引用。 When you use the assignment operator ( = ) you say, that you would like the variable on the left to store the value which is on the right.当您使用赋值运算符 ( = ) 时,您会说,您希望左侧的变量存储右侧的值。

It can be either the value of a primitive or value of the reference to an object which is stored on the heap.它可以是原语的值,也可以是对存储在堆上的 object 的引用值。

The difference between primitives and objects doesn't matter in this case actually.在这种情况下,基元和对象之间的区别实际上并不重要。 We could simplify the code to:我们可以将代码简化为:

a = {1,2,3} // we somehow declare four placeholders for values.
            // a, a[0], a[1], a[2]
temp = a[0] // here we say, that we want temp to have the same value as a[0]
            // a[0] doesn't care
a[0] = 10   // here we say, that we want a[0] to have the same value as 10
            // temp doesn't care

To achieve the behavior that would't suprise OP we would need the following class:为了实现不会让 OP 感到惊讶的行为,我们需要以下 class:

class Foo {
    int i;
    Foo(int i) {
        this.i = i;
    }
}

and

Foo[] a = new Foo[]{new Foo(1), new Foo(2)};
Foo temp = a[0];
a[0].i = 100;
System.out.println(temp.i); //100

The value temp is assigned with a[0] that at the time of the assignment is 1tempa[0]分配,在分配时为1

Then you change the value a[0] to 2. This does not change the value temp然后将值a[0]更改为 2。这不会更改值temp

To change temp you should reassign the new value with temp = a[0]要更改temp ,您应该使用temp = a[0]重新分配新值

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

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