Wednesday 1 November 2017

Remove element at given index from array

In java, arrays are fixed in size, you can’t increase/decrease the size of the array after initialization. To solve this problem, we need to return new array by not including the element at given index of input array.

Below code snippet do that.
 public static Object removeEleAtIndex(Object array, int index) {
  if (array == null || index < 0) {
   return array;
  }

  int length = Array.getLength(array);

  if (index > length - 1) {
   return array;
  }

  Object result = Array.newInstance(array.getClass().getComponentType(), length - 1);

  System.arraycopy(array, 0, result, 0, index);
  System.arraycopy(array, index + 1, result, index, length - index - 1);
  return result;
 }

Find the below working application.

ArrayUtil.java
package com.sample.collections;

import java.lang.reflect.Array;

public class ArrayUtil {

 /**
  * Remove element at given index and return new array
  * 
  * @param array
  * @param index
  * 
  * @return array, if array is null (or) index < 0 (or) index is > number of
  *         elements in array
  */
 public static Object removeEleAtIndex(Object array, int index) {
  if (array == null || index < 0) {
   return array;
  }

  int length = Array.getLength(array);

  if (index > length - 1) {
   return array;
  }

  Object result = Array.newInstance(array.getClass().getComponentType(), length - 1);

  System.arraycopy(array, 0, result, 0, index);
  System.arraycopy(array, index + 1, result, index, length - index - 1);
  return result;
 }

 public static void printArrayToConsole(Object array) {
  for (int i = 0; i < Array.getLength(array); i++) {
   System.out.println(Array.get(array, i));
  }
 }
}


Test.java
package com.sample.collections;

public class Test {

 public static void main(String args[]) {
  int[] arr = { 2, 3, 5, 7, 11, 13, 17 };

  int[] result = (int[]) ArrayUtil.removeEleAtIndex(arr, 4);
  ArrayUtil.printArrayToConsole(result);
 }
}


No comments:

Post a Comment