为什么下面的代码不抛出IndexOutOfBoundsException,并打印出9 9 6?
我是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
}
}
I am new to java. I had a doubt.
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
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是伟大的 Java 评估规则应用的另一个好例子。
Java 从左到右解析地址。
a[i]
是a[0]
的地址,然后 i 是 i 的地址,然后将 9 赋给 i,然后将 9 赋给一个[0]
。IndexOutOfBoundsException
永远不会被抛出,因为a[0]
没有越界。误解是
a[9]
,这违反了从左到右的规则This is another good example the great Java evaluation rule applies.
Java resolves the addresses from left to right.
a[i]
which is the address ofa[0]
, then i which is the address of i, then assign 9 to i, then assign 9 toa[0]
.IndexOutOfBoundsException
will never be throw sincea[0]
is not out of bound.The misconception is
a[9]
, which is against the left-to-right-rule不应该。
a[i] = i = 9(使 i 等于 9)
a[0] 也应该是 9,因为你给它分配了 9 (a[i] = i = 9),最初 a[0] 是 3
a[1] 是 6(初始值 (int[] a = {3, 6};)
你应该得到 9 9 6。
如果你执行 a[2] 那么它会给你一个 IndexOutOfBoundsException。
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};)
You should get 9 9 6.
If you do a[2] then it will give you an IndexOutOfBoundsException.