Java arrays change size

前端 未结 7 937
旧巷少年郎
旧巷少年郎 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:01

    I used the Arrays.copyOf method, like this:

        int myArray[] = {1,2,3};
        myArray = Arrays.copyOf(myArray, myArray.length+1);
        //previous line creates a copy of the array and adds one to the size
    
        myArray[3] = 12; // assign the new fourth element the value of 12
        //then loop through the array to output each element
        for(int ctr = 0; ctr

提交回复
热议问题