how to increase the size of array in java

www.‮uttual‬ri.com
how to increase the size of array in java

To increase the size of an array in Java, you can create a new, larger array and copy the elements from the original array to the new array. Here is an example of how you might do this:

int[] originalArray = {1, 2, 3, 4, 5};

int newSize = originalArray.length + 1;
int[] newArray = new int[newSize];

for (int i = 0; i < originalArray.length; i++) {
  newArray[i] = originalArray[i];
}

This code creates a new array called newArray that is one element larger than the original array. It then copies the elements from the original array to the new array using a for loop.

Alternatively, you can use the Arrays.copyOf() method, which is a utility method provided by the java.util.Arrays class, to copy the elements from the original array to a new, larger array:

int[] originalArray = {1, 2, 3, 4, 5};

int newSize = originalArray.length + 1;
int[] newArray = Arrays.copyOf(originalArray, newSize);

This code creates a new array called newArray that is one element larger than the original array, and copies the elements from the original array to the new array using the Arrays.copyOf() method.

Once you have increased the size of the array, you can add new elements to the end of the array by assigning values to the unused elements at the end of the array. For example:

newArray[newSize - 1] = 6;  // Add a new element at the end of the array

Keep in mind that increasing the size of an array in this way can be time-consuming, as it requires creating a new array and copying all of the elements from the original array to the new array. If you need to frequently add and remove elements from an array, you may want to consider using a different data structure, such as an ArrayList, which provides more flexibility and better performance when inserting and deleting elements.

Created Time:2017-11-01 20:42:56  Author:lautturi