Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to increase an array's length

Tags:

I have a quick question. I have an integer array in java that needs its length to vary throughout the class. Specifically, I need it to increase by one in certain situations. I tried it like this.

        sbgHeadX = new int[ numberOfSBG ]; 

I would increase the integer variable numberOfSBG when I needed to, but I don't think this works. Is there any other way?

like image 935
kullalok Avatar asked Apr 21 '12 01:04

kullalok


People also ask

Can you change an array's length?

The simple answer is that you cannot do this. Once an array has been created, its size cannot be changed. Instead, an array can only be "resized" by creating a new array with the appropriate size and copying the elements from the existing array to the new one.

Can you increase the size of an array in C++?

You can't change the size of the array, but you don't need to. You can just allocate a new array that's larger, copy the values you want to keep, delete the original array, and change the member variable to point to the new array. Allocate a new[] array and store it in a temporary pointer.


1 Answers

If you don't want or cannot use ArrayList, then there is a utility method:

Arrays.copyOf()  

that will allow you to specify new size, while preserving the elements.

like image 192
Jakub Zaverka Avatar answered Oct 07 '22 19:10

Jakub Zaverka