简体   繁体   English

java数组中的意外增量结果

[英]unexpected increment result in java array

While learning how to declare, initialize and access the array elements in java, I wrote this simple code: 在学习如何声明,初始化和访问java中的数组元素时,我编写了这个简单的代码:

class ArrayAccess{

    public static void main(String args[]){
        int[] a;
        a = new int[4];
        a[0] = 23;
        a[1] = a[0]*2;
        a[2] = a[0]++;
        a[3]++;
        int i = 0;
        while(i < a.length){
            System.out.println(a[i]);
            i++;

        }
    }
}

But I am getting unexpected output. 但我得到了意想不到的输出。

The output I am getting is: 我得到的输出是:

24     

46

23

1

So, 所以,

Why 24 instead of 23 as the value of a[0] ? 为什么24而不是23作为a[0]的值? If this is due increment of a[0] at a[2] then why a[1] 's element is 46 and not 48 . 如果这是a[2] a[0]增量,则为什么a[1]的元素是46而不是48

why 23 instead of 24 as the value of a[2] ? 为什么23而不是24作为a[2]的值?

a[2] = a[0]++; incremnets a[0] after copying the value into a[2] 将值复制到[2]后,递增a [0]

Its the same as: 它与以下相同:

a[2] = a[0];
a[0]+=1;

If you want to increment the value before the assignation use a[2] = ++(a[0]); 如果要在赋值前增加值,请使用a[2] = ++(a[0]);

This ist the same as: 这与以下相同:

a[0]+=1;
a[2] = a[0];
a[2] = a[0]++; 

is

  int temp = a[0];
  a[2] = a[0];
  a[0] = temp + 1;

Because of the following line: 由于以下行:

a[2] = a[0]++;

Increment (++) has a side effect of incrementing the right-side value. 增量(++)具有增加右侧值的副作用。 Otherwise you should use: 否则你应该使用:

a[2] = a[0]+1;

Another example is the similar concept of ++number. 另一个例子是++编号的类似概念。 If you had written: 如果你写了:

a[2] = ++a[0];

a[0] would be incremented, and THEN added to a[2]. a [0]将递增,然后添加到[2]。 So in a[2] you would have: 24 所以在[2]中你会得到:24

small modification in your prog required 你所需要的小修改

class ArrayAccess{ class ArrayAccess {

public static void main(String args[]){
   int referenceNumber= 23;
    int[] a;
    a = new int[4];
    a[0] = referenceNumber;
    a[1] = a[0]*2;
    a[2] = referenceNumber++;
    a[3]++;
    int i = 0;
    while(i < a.length){
        System.out.println(a[i]);
        i++;

    }
}

} }

now lets come to questions 现在让我们来问问题

Why 24 instead of 23 as the value of a[0]? 为什么24而不是23作为a [0]的值? If this is due increment of a[0] at a[2] then why a[1]'s element is 46 and not 48. 如果这是[2]的[0]的正确增量,则为什么[1]的元素是46而不是48。

yes it is due of increment of a[0] at a[2]. 是的,这是由于[2]的a [0]的增量。 But point is the moment u are doing a[1] = a[0]*2; 但关键是你正在做[1] = a [0] * 2的那一刻; its not incremented yet. 它还没有增加。

why 23 instead of 24 as the value of a[2]? 为什么23而不是24作为a [2]的值?

you are doing a[2] = a[0]++; 你正在做[2] = a [0] ++; whats happening is first value of a[0] is assigned to a[2] and then ultimately value at a[0] is incremented not at a[2] 发生的是a [0]的第一个值被分配给[2],然后最终a [0]的值增加而不是[2]

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

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