简体   繁体   English

Java中此ArrayIndexOutOfBoundsException的原因是什么?

[英]What is the reason for this ArrayIndexOutOfBoundsException in Java?

Java throws an ArrayIndexOutOfBoundsException error when I run this function: 运行此函数时,Java引发ArrayIndexOutOfBoundsException错误:

public int[] copySecondSlice(int[] array) {
    int[] newArray = new int[array.length/2];
    for (int i = array.length/2; i < array.length; i++) {
        assert i == 1;
        newArray[i] = array[i];
    }
    return newArray;
}

I tried multiple assets to check that i is superior to 0 and inferior to my array's length, but nothing does the trick. 我尝试了多种资产,以检查我是否优于0且小于数组的长度,但没有任何办法。 Could someone help me understand my mistake here? 有人可以帮我理解我的错误吗?

Simply because you are trying to reach the index which is out of bound of array new Array. 仅仅是因为您试图达到超出数组new Array范围的索引。

See 看到

int[] newArray = new int[array.length/2];

Here you declare length of newArray is array.length/2 在这里,您声明newArray的长度为 array.length / 2

And

for (int i = array.length/2; **i < array.length**; i++) {
 newArray[**i**] = array[i];

Your condition will allow for to iterate till array.length-1 so newArray is supposed to fill till that index ie array.length-1 . 您的条件将允许迭代到array.length-1因此应该将newArray填充到该索引即array.length-1 But our length of newArray is only array.length/2 so it is going out of bound. 但是我们newArray的长度仅为array.length/2所以超出了范围。

as @RP said you can correct it. 正如@RP所说,您可以纠正它。

newArray index should start from 0 instead of i . newArray索引应从0而不是i Something like 就像是

  for (int j=0, i = array.lenght/2; i < array.length; i++, j++) { 
       ...
       newArray[j] = array[i]; 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM