Java arrays change size

前端 未结 7 922
旧巷少年郎
旧巷少年郎 2020-12-10 09:02

I need to change the size of an array, but I cannot simply create another - It needs the same name so I can pass it to a method. Specifically, I need the array to have twice

相关标签:
7条回答
  • 2020-12-10 10:08

    An array is an Array. Here you can dynamically increase the size of the array, keeping its name. In this instance, it is increasing its size until the sum of its indexes reaches the goal, which is 100.

        int goal = 0;
        int[] arr = {1,2,3};
    
        int i = 0;
        while (goal<100){
            goal+=arr[i];
            i++;
            int[] tmpArray = new int[arr.length];
            for (int j = 0; j < arr.length; j++) {
                tmpArray[j] = arr[j];
            }
            if(i>=arr.length){
                arr = new int[arr.length+1];
                for (int j = 0; j < tmpArray.length; j++) {
                    arr[j] = tmpArray[j];
                }
                arr[arr.length-1] = 1;
            }
        }
    
    0 讨论(0)
提交回复
热议问题