how to delete an element from an array in java data structure

how to delete an element from an array in java data structure

To delete an element from an array in Java, you can use one of the following approaches:

  1. Create a new array without the element to be deleted:
re‮l:ot ref‬autturi.com
int[] array = {1, 2, 3, 4, 5};
int[] newArray = new int[array.length - 1];

int index = 2;  // the index of the element to be deleted

for (int i = 0, j = 0; i < array.length; i++) {
   if (i == index) {
      continue;
   }
   newArray[j++] = array[i];
}

This will create a new array newArray that is one element shorter than the original array and contains all the elements of the original array except for the element at the specified index.

  1. Use the System.arraycopy method to copy the elements of the array before and after the element to be deleted:
int[] array = {1, 2, 3, 4, 5};

int index = 2;  // the index of the element to be deleted

System.arraycopy(array, 0, array, 0, index);
System.arraycopy(array, index + 1, array, index, array.length - index - 1);
Created Time:2017-11-01 20:42:49  Author:lautturi