简体   繁体   中英

Java arrays change size

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 as many terms as it used to. Is this possible to do with one array? Can I copy data from array A to array B, then make A reference the same data as B with A = B; ?

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

Yes, your array variable may reference an array of the same type but different size.

For changing it internally, an ArrayList might be more easy to use.

You need to create a new array since those are static in size. Then use srcArray = Arrays.copyOf(srcArray, srcArray.length * 2); .

Alternatively you might want to think about using a list instead of an array. ArrayList is internally backed by an array which will double its size when needed.

That's not how arrays in Java work:

int[] anArray;
anArray = new int[10];

for (int i = 0; i < 10; ++i) {
  // ...
}

int[] secondArray = anArray;

// Grow "anArray" via secondArray to 20 please:
secondArray = new int[20]; // No way to alter anArray with this - now two arrays

The closest work around is to make the array the full size when you allocate it, but not use the whole of it until you're ready. Ie you want to pre-allocate all the space you'll ever need in it.

int[] anArray;
anArray = new int[20];

for (int i = 0; i < 10; ++i) { // Still < 10 here
  // ...
}

int[] secondArray = anArray;
// no need to change the array, it's already big enough

Either that or use one of the many containers provided.

int[] a = new int[5];
// fill a
int[] b = Arrays.copyOf(a, 10);

与 Array 相比,使用 ArrayList 更好

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;
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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