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


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]

Lakshmi Srinivas
Lakshmi Srinivas

Programmer / Analyst / Technician

Updated on: 19-Dec-2019

158 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements