YouTip LogoYouTip

Arrays Insert

## Java Array Insertion: How to Insert Elements into an Array In Java, standard arrays have a fixed size. Once an array is created, its length cannot be dynamically changed. To insert an element into an existing array, you must create a new, larger array, copy the elements from the original array, and insert the new element at the desired position. This tutorial demonstrates how to sort an array, find the correct insertion index using binary search, and insert an element at a specific index using a custom helper method. --- ## Conceptual Overview To insert an element into a fixed-size array at a specific index, the following steps are required: 1. **Create a new array** with a capacity of `original.length + 1`. 2. **Copy elements** from the original array up to the target insertion index into the new array. 3. **Insert the new element** at the target index. 4. **Copy the remaining elements** from the original array (starting from the insertion index) to the new array, shifting their positions by one. --- ## Code Example The following complete Java program demonstrates how to: 1. Sort an array using `Arrays.sort()`. 2. Determine the correct insertion point for a new element using `Arrays.binarySearch()`. 3. Perform the array insertion using `System.arraycopy()`. ```java import java.util.Arrays; public class MainClass { public static void main(String args[]) throws Exception { // Initialize an unsorted integer array int array[] = { 2, 5, -2, 6, -3, 8, 0, -7, -9, 4 }; // Sort the array in ascending order Arrays.sort(array); printArray("Sorted array", array); // Search for the element '1' in the sorted array int index = Arrays.binarySearch(array, 1); System.out.println("Position of element 1 (negative value means not found): " + index); // Calculate the insertion index if the element is not found. // binarySearch returns: -(insertion point) - 1 if the key is not present. int newIndex = -index - 1; // Insert the element '1' at the calculated index array = insertElement(array, 1, newIndex); printArray("Array after inserting element 1", array); } /** * Helper method to print the array elements and its length. */ private static void printArray(String message, int array[]) { System.out.println(message + ": [length: " + array.length + "]"); for (int i = 0; i < array.length; i++) { if (i != 0) { System.out.print(", "); } System.out.print(array); } System.out.println(); } /** * Inserts an element into a specific index of an array. * * @param original The source array. * @param element The value to insert. * @param index The index at which to insert the value. * @return A new array containing the inserted element. */ private static int[] insertElement(int original[], int element, int index) { int length = original.length; // Create a new array with size + 1 int destination[] = new int[length + 1]; // Copy elements before the insertion index System.arraycopy(original, 0, destination, 0, index); // Insert the new element destination = element; // Copy the remaining elements, shifting them to the right System.arraycopy(original, index, destination, index + 1, length - index); return destination; } } ``` --- ## Output When you run the program, it produces the following output: ```text Sorted array: [length: 10] -9, -7, -3, -2, 0, 2, 4, 5, 6, 8 Position of element 1 (negative value means not found): -6 Array after inserting element 1: [length: 11] -9, -7, -3, -2, 0, 1, 2, 4, 5, 6, 8 ``` --- ## Key Methods Explained ### 1. `Arrays.binarySearch(array, key)` This method searches the specified array for the specified value using the binary search algorithm. * **Prerequisite:** The array must be sorted prior to making this call. * **Return Value:** If the key is found, it returns the index of the search key. If it is not found, it returns `-(insertion point) - 1`. The *insertion point* is defined as the point at which the key would be inserted into the array to maintain sorted order. ### 2. `System.arraycopy(src, srcPos, dest, destPos, length)` This is a highly optimized native method used to copy data from one array to another. * `src`: The source array. * `srcPos`: Starting position in the source array. * `dest`: The destination array. * `destPos`: Starting position in the destination data. * `length`: The number of array elements to be copied. --- ## Alternative Approaches While manual copying using `System.arraycopy()` is highly performant, you can also consider these alternatives for dynamic array manipulation: * **`ArrayList`**: If you need to perform frequent insertions and deletions, use `ArrayList` instead of a primitive array. It handles resizing automatically via the `add(int index, E element)` method. * **`Apache Commons Lang`**: If you have the library in your project classpath, you can use `ArrayUtils.add(array, index, element)` to perform this operation in a single line of code.
← Arrays UpperboundString Optimization β†’