Easy Tutorial
❮ Java Map Interface Net Filetime ❯

Java Example - Array Element Addition

Java Examples

The following example demonstrates how to use the sort() method to sort a Java array and how to use the insertElement() method to insert an element into the array. We have also defined the printArray() method to print the array:

MainClass.java File

import java.util.Arrays;

public class MainClass {
   public static void main(String args[]) throws Exception {
      int array[] = { 2, 5, -2, 6, -3, 8, 0, -7, -9, 4 };
      Arrays.sort(array);
      printArray("Sorted Array", array);
      int index = Arrays.binarySearch(array, 1);
      System.out.println("Element 1's position (negative if not present): " + index);
      int newIndex = -index - 1;
      array = insertElement(array, 1, newIndex);
      printArray("Array after adding element 1", array);
   }
   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[i]);
      }
      System.out.println();
   }
   private static int[] insertElement(int original[], int element, int index) {
      int length = original.length;
      int destination[] = new int[length + 1];
      System.arraycopy(original, 0, destination, 0, index);
      destination[index] = element;
      System.arraycopy(original, index, destination, index + 1, length - index);
      return destination;
   }
}

The output of the above code is:

Sorted Array: [length: 10] -9, -7, -3, -2, 0, 2, 4, 5, 6, 8
Element 1's position (negative if not present): -6
Array after adding element 1: [length: 11] -9, -7, -3, -2, 0, 1, 2, 4, 5, 6, 8

Java Examples

❮ Java Map Interface Net Filetime ❯