【问题标题】:Why does this result in an ArrayIndexOutOfBoundsException at run-time? [duplicate]为什么这会在运行时导致 ArrayIndexOutOfBoundsException? [复制]
【发布时间】:2018-10-23 08:03:56
【问题描述】:

这是代码:

public class Test {
    public static void main(String[] args) {
        int[] a= new int[3];
        System.out.print(a[a.length]);
    }
}

为什么这会在运行时导致 ArrayIndexOutOfBoundsExceptionwill?

【问题讨论】:

  • 因为索引 从 0 到 2 而不是 从 1 到 3 :)
  • 更改为System.out.print(a[a.length - 1])
  • 由于newint[3];,它不应该编译
  • 还有publicclassTest

标签: java arrays


【解决方案1】:

a.length返回数组的元素个数,这里是3。

数组索引从 0 开始。有 3 个元素,它是 0,1,2。

没有索引 3,因此例外。

【讨论】:

    【解决方案2】:

    它从0开始,所以你必须更改为[a.length - 1]

     public class Test{
           public static void main(String []args){
              int[] a= new int[3];
              System.out.print(a[a.length-1]);
           }
        }
    

    【讨论】:

      【解决方案3】:

      索引从0 开始(不是1)。因此,在您的情况下,a 具有索引 012

      但您正在尝试访问索引3lengthsize)。

      请改用System.out.print(a[a.length]-1);

      【讨论】:

        【解决方案4】:

        你应该使用它:

        public class Test{
        
             public static void main(String []args){
                int[] a= new int[3];
                System.out.print(a[a.length-1]);
            }
        }
        

        说明:

        a.length 将返回 length,即 3(3 个现有字段)。 但是a[3] 的索引计算从 0 开始,一直到 2。 用 -1 减少长度会返回最后一个真正存在的索引 (2)。

        所以a[a.length] (= a[3]) 会导致数组索引越界异常。

        【讨论】:

        • 没有解释的代码通常无助于理解问题
        【解决方案5】:

        这是IndexOutOfBoundsException的层次结构:

         java.lang.Object
            java.lang.Throwable
                java.lang.Exception
                    java.lang.RuntimeException
                        java.lang.IndexOutOfBoundsException 
        

        有时很难解决。在这些时刻,您可以使用 IDLE 调试器。它将在图形界面中向您显示每次迭代时每个变量的值。

        您可以使用Eclipse 调试器、NetbeansVisual Studio 代码、Atom 扩展也可以。

        【讨论】:

          猜你喜欢
          • 2014-01-01
          • 1970-01-01
          • 2011-06-29
          • 2011-11-27
          • 1970-01-01
          • 2021-02-20
          • 2013-01-18
          • 1970-01-01
          相关资源
          最近更新 更多