Java数组改变了大小

JTT*_*OTE 3 java arrays

我需要更改数组的大小,但我不能简单地创建另一个 - 它需要相同的名称,所以我可以将它传递给一个方法.具体来说,我需要数组的术语数量是以前的两倍.这可能与一个阵列有关吗?我可以将数据从数组A复制到数组B,然后使A引用与B相同的数据,其中A = B; ?

小智 5

我使用了Arrays.copyOf方法,如下所示:

    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<myArray.length; ctr++){
        System.out.println(myArray[ctr]);
    }
Run Code Online (Sandbox Code Playgroud)