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?
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With