如何在 Java 中向陣列的中間點新增元素?


Apache commons 提供了一個名為org.apache.commons.lang3的庫,以下是向專案新增庫的 maven 依賴項。

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

此包提供了一個名為ArrayUtils的類。可以使用此類的add()方法向陣列中的特定位置新增元素。

示例

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));
   }
}

輸出

[23, 93, 30, 40, 56, 92, 39]

更新於: 2019-12-19

201 次瀏覽

開啟你的 職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.