无法解释copyOfRange(int [] a,int from,int to)函数的行为

时间:2015-01-08 21:56:00

标签: java arrays copy

我试图使用Arrays静态函数copyOfRegion进行一些切片复制。我的代码如下:

public class MyJavaArrays {
    static int[] findEquilibPoint(int[] A) {

        int[] resArray = {-1};
        /* 
         * Our equilibrium condition is that the index must be between 0 and length
         * of the input array
         *
         */
         int l = A.length;
         int sum_l = 0;
         int sum_r = 0;
         int j = 0;
         for(int i=1; i<l-1; i++) {
            sum_l=0;
            sum_r=0;

            int[] b1 = Arrays.copyOfRange(A,0,i-1);
            int[] b2 = Arrays.copyOfRange(A,i+1,l-1);
            System.out.println("START HERE..............\n");
            for (int s: b1)
                System.out.print(s + ", ");
            System.out.println("\n............");
            for (int s: b2)
                System.out.print(s + ", ");
            System.out.println("\n............");
            for (int x: b1){sum_l += x;}
            for (int y: b2){sum_r += y;}
            System.out.println(sum_l+" ?= "+sum_r);
            /* if the sums are equal, we have an equilibrium point */
            if (sum_l == sum_r) {
            resArray[j] = i;
            j++;
            }
         }
         return resArray;
    }
    public static void main(String[] args) {
        int[] A = {-1, 3, -4, 5, 1,-6, 2, 1};
        findEquilibPoint(A);        

    }

我尝试使用i(l-1,l,l + 1)的不同限制来运行它,我的调查显示copyOfRange()方法实际上正在执行to-1。我上面代码的输出如下:

START HERE..............


............
-4, 5, 1, -6, 2, 
............
0 ?= -2
START HERE..............

-1, 
............
5, 1, -6, 2, 
............
-1 ?= 2
START HERE..............

-1, 3, 
............
1, -6, 2, 
............
2 ?= -3
START HERE..............

-1, 3, -4, 
............
-6, 2, 
............
-2 ?= -4
START HERE..............

-1, 3, -4, 5, 
............
2, 
............
3 ?= 2
START HERE..............

-1, 3, -4, 5, 1, 
............

............
4 ?= 0

我可以清楚地看到,在第一次&#34; START HERE ............&#34;声明,什么都没有!我有点困惑,但这是否是任何已知的错误?我还去Tutorialspoint website检查我对copyOfRange的理解是否错误。但似乎这个小伙子正在做我想做的事。

任何想法/建议任何人?

0 个答案:

没有答案