[英]What are the semantics of java's postfix increment operator on the left side of an assignment statement and why do they differ from the right side?
I was working on a leetcode question [1] and noticed something that caught my eye. 我工作在本文给出了问题[1],并发现了一些吸引我眼球。
When I write a line of code as: 当我编写一行代码时:
nums[i] = nums[(i++)+count];
I pass all the tests and my answer is accepted. 我通过了所有测试,答案被接受。 If however I change the same line to:
但是,如果我将同一行更改为:
nums[i++] = nums[i+count];
I get an ArrayOutOfBounds exception. 我收到了ArrayOutOfBounds异常。 Why is this?
为什么是这样?
Here is the full code: 这是完整的代码:
public void moveZeroes(int[] nums) {
int count = 0, i = 0;
while(i+count < nums.length){
if(nums[i+count] == 0)
count++;
else
nums[i] = nums[(i++)+count];
}
for(;i<nums.length; i++)
nums[i] = 0;
}
[1] https://leetcode.com/problems/move-zeroes/ [1] https://leetcode.com/problems/move-zeroes/
The answer lies in JLS 15.26.1 . 答案在于JLS 15.26.1 。 Basically, this is the order of things in the case of
基本上,这是
nums[i++] = nums[i+count];
nums
is evaluated (as part of the left-hand side) nums
被评估(作为左侧的一部分) i++
is evaluated to find the index; i++
进行评估以找到索引; the result is the original value of i
, but i
is then incremented i
的原始值,但随后i
递增 nums
is evaluated (as part of the right-hand side) nums
被评估(作为右侧的一部分) i+count
is evaluated; i+count
被评估; note that this uses the already incremented value of i
, which is why you're getting an exception i
值,这就是为什么您遇到异常的原因 The important part is that the left operand of the assignment operator is evaluated before the expression on the right operand. 重要的是,赋值运算符的左操作数在右操作数上的表达式之前进行求值。 So the side-effect while evaluating the array index expression in the left operand affects the evaluation of the right operand.
因此,在评估左侧操作数中的数组索引表达式时的副作用会影响右侧操作数的评估。
In the first example, i
is being incremented after it is done being used in that iteration. 在第一个示例中,在迭代中使用完
i
后,将对其进行递增。
nums[(i++)+count];
means increment i
by one after evaluating the equivalent of nums[(i) + count]
. 表示在评估
nums[(i) + count]
的等效项后, i
递增1。
In the second example, i
is being incremented before nums[ i +count];
在第二个示例中,
i
在nums[ i +count];
之前递增nums[ i +count];
. 。
nums[i++]
means increment i
by one after evaluating the equivalent of nums[i]
. 表示在评估
nums[i]
的等效项后, i
递增1。
When the code gets to nums[ i + count];
当代码达到
nums[ i + count];
, i
has already been incremented. ,
i
已经增加了。 This is results in an ArrayOutOfBounds exception in the case that i + count
is equal to nums.length
. 在
i + count
等于nums.length
的情况下,这将导致ArrayOutOfBounds异常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.