I am new to java. I had a doubt.
我是java的新手。我有一个疑问。
class ArrTest{
public static void main(String args[])
{
int i = 0;
int[] a = {3,6};
a[i] = i = 9;
System.out.println(i + " " + a[0] + " " + a[1]); // 9 9 6
}
}
2 个解决方案
#1
8
This is another good example the great Java evaluation rule applies.
这是伟大的Java评估规则适用的另一个好例子。
Java resolves the addresses from left to right. a[i]
which is the address of a[0]
, then i which is the address of i, then assign 9 to i, then assign 9 to a[0]
.
Java从左到右解析地址。 a [i]是[0]的地址,然后i是i的地址,然后将9分配给i,然后将9分配给a [0]。
IndexOutOfBoundsException
will never be throw since a[0]
is not out of bound.
The misconception is a[9]
, which is against the left-to-right-rule
IndexOutOfBoundsException永远不会抛出,因为[0]没有超出范围。误解是[9],这是违反从左到右的规则
#2
0
It should not.
它不应该。
a[i] = i = 9 (makes i equal to 9) a[0] should also be 9 since you assigned 9 to it (a[i] = i = 9), Initially a[0] was 3 and a[1] is 6 (initial value (int[] a = {3, 6};)
a [i] = i = 9(使i等于9)a [0]也应该是9,因为你为它分配了9(a [i] = i = 9),最初a [0]是3和a [ 1]是6(初始值(int [] a = {3,6};)
You should get 9 9 6.
你应该得到9 9 6。
If you do a[2] then it will give you an IndexOutOfBoundsException.
如果你做[2]那么它会给你一个IndexOutOfBoundsException。
#1
8
This is another good example the great Java evaluation rule applies.
这是伟大的Java评估规则适用的另一个好例子。
Java resolves the addresses from left to right. a[i]
which is the address of a[0]
, then i which is the address of i, then assign 9 to i, then assign 9 to a[0]
.
Java从左到右解析地址。 a [i]是[0]的地址,然后i是i的地址,然后将9分配给i,然后将9分配给a [0]。
IndexOutOfBoundsException
will never be throw since a[0]
is not out of bound.
The misconception is a[9]
, which is against the left-to-right-rule
IndexOutOfBoundsException永远不会抛出,因为[0]没有超出范围。误解是[9],这是违反从左到右的规则
#2
0
It should not.
它不应该。
a[i] = i = 9 (makes i equal to 9) a[0] should also be 9 since you assigned 9 to it (a[i] = i = 9), Initially a[0] was 3 and a[1] is 6 (initial value (int[] a = {3, 6};)
a [i] = i = 9(使i等于9)a [0]也应该是9,因为你为它分配了9(a [i] = i = 9),最初a [0]是3和a [ 1]是6(初始值(int [] a = {3,6};)
You should get 9 9 6.
你应该得到9 9 6。
If you do a[2] then it will give you an IndexOutOfBoundsException.
如果你做[2]那么它会给你一个IndexOutOfBoundsException。