How to add elements to the midpoint of an array in Java?

Java 8Object Oriented ProgrammingProgramming

Apache commons provides a library named org.apache.commons.lang3 and, following is the maven dependency to add library to your project.

<dependencies>
   <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-lang3</artifactId>
      <version>3.0</version>
   </dependency>
</dependencies>

This package provides a class named ArrayUtils. You can add an element at a particular position in an array using the add() method of this class.

Example

import java.util.Arrays;
import org.apache.commons.lang3.ArrayUtils;

public class AddingElementToMidPoint {
   public static void main(String args[]) {
      int[] myArray = {23, 93, 30, 56, 92, 39};
      int eleToAdd = 40;
      int position= myArray.length/2;
      int [] result = ArrayUtils.add(myArray, position, eleToAdd);
      System.out.println(Arrays.toString(result));
   }
}

Output

[23, 93, 30, 40, 56, 92, 39]
raja
Published on 08-Jan-2018 16:59:19
Advertisements