To resize the array in Java, you should follow several steps. The basic idea to create an empty array list with the needed length. And copy all elements from the first array list to the second.
Resize the array list in Java example. Step-by-step implementation.
If you want to resize the array list, you have to follow several steps:
- Create a new array list with the needed length.
//The value of how many capacity suppose to be in a new array
int capacity = 15;
//Creating empty array with needed capacity and then we will copy all values from our array
int[] temporaryArray = new int[capacity];
- Copy elements from list one to a new list. For that purpose, you may use basically for each loop.
//Now we need to copy values from first to second
for (int i = 0; i < intArray.length; i++) {
//Setting first element of the temporary array to the value of first array... Etc...
temporaryArray[i] = intArray[i];
}
The full code example:
private void resizeOfTheArray() {
//Created a new array of integers
int[] intArray = new int[]{1, 5, 3, 44, 5, 17, 78, 13, 9, 2};
//Get the length of the array
int arrayLength = intArray.length;
//Showing in logs size of the array before resize
Log.d("arrayList", "Old size of array: " + arrayLength);
//The value of how many capacity suppose to be in a new array
int capacity = 15;
//Creating empty array with needed capacity and then we will copy all values from our array
int[] temporaryArray = new int[capacity];
//We have created new empty array now we need to copy values from first to second
for (int i = 0; i < intArray.length; i++) {
//Setting first element of the temporary array to the value of first array... Etc...
temporaryArray[i] = intArray[i];
}
//Setting first array to temporary and adjusting the size of it
intArray = temporaryArray;
//Showing size of the array after resize
Log.d("arrayList", "New size of array: " + intArray.length);
}
In this article, you figured out the easiest way to resize an array list in java.
Full code and more examples in my facebook group.
Useful links:
- Search for an element in the Linked List in Java
- Deleting an item in the Linked List in Java (Android Studio)
- Adding items to the Linked List in Java.
- Getting the length (size) of Linked List in Java (Android Studio)
- Two ways to implement a Linked List in Java. Example.
- Reversing the linked list.
- Middle of the linked list example.
- Find the nth element from the last in Linked List (Java)
- Removing duplicates from the linked list
- Inserting an item in the linked list (Java)
Leave Any Questions Related To This Article Below!