简体   繁体   English

java.lang.ArrayIndexOutOfBoundsException:-6

[英]java.lang.ArrayIndexOutOfBoundsException: -6

Any solution for this i need to swap element x with y in unsorted array ,x and y are in array 任何解决方案我都需要在未排序的数组中用y交换元素x,x和y在数组中

I have this error for array lengths >= 6. The code works for tabX[] < 6 length. 我有这个错误的数组长度> = 6.该代码适用于tabX [] <6长度。

java.lang.ArrayIndexOutOfBoundsException:-6. java.lang.ArrayIndexOutOfBoundsException:-6。

int tabX[] = {
    20, 40, 50, 60, 80, 70
};
int elemA[];
int elemB[];
int sumA = 0;
int sumB = 0;
int tmp, lastButOne;
Arrays.sort(tabX);
while (sumA > sumB || sumA == 0 || sumB == 0) {
    for (int i = 0; i < tabX.length; i++) {
        sumA = 0;
        sumB = 0;
        elemA = new int[tabX.length - (i + 1)];
        elemB = new int[i + 1];
        for (int j = 0; j < tabX.length - (i + 1); j++) {
            elemA[j] = tabX[j];
            sumA += elemA[j];
        }
        for (int k = 0; k < elemB.length; k++) {
            elemB[k] = tabX[tabX.length - (k + 1)]; //i
            sumB += tabX[tabX.length - (k + 1)];
        }
        if (sumA == sumB) {
            System.out.println("Secventa A = " + Arrays.toString(elemA));
            System.out.println("Secventa B = " + Arrays.toString(elemB));
            break;
        } else if (sumA < sumB) {
            System.out.println("Not a solution");
            break;
        }
        /************ Swap element in array****************/
        lastButOne = tabX[tabX.length - (i + 2)];
        int indexOfLastButOne = Arrays.binarySearch(tabX, lastButOne);
        tmp = tabX[i];
        tabX[indexOfLastButOne] = tmp; //here is error
        tabX[i] = lastButOne;
    } //for
} //while

Well, that's exactly how Arrays.binarySearch works: when the actual element you're asking for isn't there, you get the -(insertion point) - 1, which happens to be -6 in your case. 好吧,这就是Arrays.binarySearch的工作原理:当你要求的实际元素不存在时,你得到 - (插入点) - 1,在你的情况下恰好是-6。

But also: binarySearch assumes the elements are sorted, so if they're not, it can indeed happen that it isn't found, even if the value is in the list. 但是:binarySearch假设元素是排序的,所以如果它们不是,它确实会发生它找不到,即使值在列表中。

It would be helpfull if you pointed out where the exception is thrown (add a comment like // AIOOBE here . From looking at your code, I guess you get a negative return value from Arrays.binarySearch() : 如果你指出抛出异常的位置会// AIOOBE here添加一个像// AIOOBE here这样的注释。从查看你的代码,我猜你从Arrays.binarySearch()得到一个负的返回值:

    int indexOfLastButOne = Arrays.binarySearch(tabX, lastButOne);
    ...
    tabX[indexOfLastButOne] = tmp; // ArrayOutOfBoundsException

From the documentation of Arrays.binarySearch : returns index of the search key, if it is contained in the array; Arrays.binarySearch的文档中:返回搜索键的索引,如果它包含在数组中; otherwise, (-(insertion point) - 1) . 否则, ( - (插入点) - 1)

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

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