【问题标题】:Why does this code cause an ArrayIndexOutOfBoundsException? [duplicate]为什么这段代码会导致 ArrayIndexOutOfBoundsException? [复制]
【发布时间】:2019-05-14 08:26:57
【问题描述】:

我试图了解为什么我的代码会导致 ArrayIndexOutOfBoundsException。谁能给我解释一下?

public class Test {
    final static int x[] = new int[5];
    public static void main(String[] args) {
    final int x = new Test().x[5];
    if (x <= 10)
        System.out.println("javachamp");
    }
}

【问题讨论】:

标签: java arrays indexoutofboundsexception


【解决方案1】:

问题是数组的索引从 0 开始。给定数组大小为 5,数组的最后一个元素是 x[4](第一个元素是 x[0])

【讨论】:

  • 数组的索引从 0 开始,数组本身具有你作为第一个元素放置的任何值
  • 谢谢,这是一个很好的说明。我会编辑我的答案
猜你喜欢
  • 2013-01-18
  • 2014-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-03
  • 2011-03-16
  • 2012-08-27
  • 1970-01-01
  • 2020-08-20
相关资源
最近更新 更多