【问题标题】:java.lang.ArrayIndexOutOfBoundsException error?java.lang.ArrayIndexOutOfBoundsException 错误?
【发布时间】:2012-12-02 22:02:59
【问题描述】:

我试图拆分一个数组,将一个部分存储在一个数组中,将另一部分存储在另一个数组中。然后我试图翻转 2 并将它们存储在一个新数组中。这就是我所拥有的

public int[] flipArray(){
        int value = 3;
        int[] temp1 = new int[value];
        int[] temp2 = new int[(a1.length-1) - (value+1)];
        int[] flipped = new int[temp1.length+temp2.length];

    System.arraycopy(a1, 0, temp1, 0, value);
    System.arraycopy(a1, value+1, temp2, 0, a1.length-1);
    System.arraycopy(temp2, 0, flipped, 0, temp2.length);
    System.arraycopy(temp1, 0, flipped, temp2.length, temp1.length); 
            return flipped;
    }
    private int[]a1={1,2,3,4,5,6,7,8,9,10};

【问题讨论】:

标签: java indexoutofboundsexception arrays


【解决方案1】:

当您想要访问范围 [0, length - 1] 之外的数组元素时,您会得到 ArrayIndexOutOfBoundsException;

您可以自己找到问题,如果您使用调试器,或者 在每次调用 System.arraycopy 之前放置一个 System.out.println(text),您可以在其中输出源数组和目标数组的数组长度以及要复制的元素数

【讨论】:

    【解决方案2】:

    您的索引和数组长度已关闭:

    public int[] flipArray(){
        int value = 3;
        int[] temp1 = new int[value];
        int[] temp2 = new int[a1.length - value];
        int[] flipped = new int[a1.length];
    
        System.arraycopy(a1, 0, temp1, 0, value);
        System.arraycopy(a1, value, temp2, 0, temp2.length);
        System.arraycopy(temp2, 0, flipped, 0, temp2.length);
        System.arraycopy(temp1, 0, flipped, temp2.length, temp1.length); 
        return flipped;
    }
    private int[]a1={1,2,3,4,5,6,7,8,9,10};
    

    关键是要明白System.arraycopy不会复制最后一个索引处的元素。

    【讨论】:

      【解决方案3】:

      摆脱不必要的索引操作:

      public int[] flipArray(){
      int value = 3;
      int[] temp1 = new int[value];
      int[] temp2 = new int[a1.length - value];
      int[] flipped = new int[temp1.length+temp2.length];
      
      System.arraycopy(a1, 0, temp1, 0, value);
      System.arraycopy(a1, value, temp2, 0, temp2.length);
      System.arraycopy(temp2, 0, flipped, 0, temp2.length);
      System.arraycopy(temp1, 0, flipped, temp2.length, temp1.length); 
      }
      

      【讨论】:

        【解决方案4】:

        这一行是错误的:

        System.arraycopy(a1, value+1, temp2, 0, a1.length-1);
        

        您从位置 4 开始,想要复制 9 个元素。这意味着它会尝试将数组中索引 4 的元素复制到 12。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-03-27
          • 2018-09-10
          相关资源
          最近更新 更多