• Java 資料結構教程

陣列中插入元素



插入操作是在陣列中插入一個或多個數據元素。根據需要,可以在陣列的開頭、結尾或任何給定索引處新增新元素。

演算法

LA為一個具有N個元素的線性陣列(無序),K是一個正整數,使得K<=N。以下是將ITEM插入到LA的第K個位置的演算法:

Step 1 - Start
Step 2 - Set J = N
Step 3 - Set N = N+1
Step 4 - Repeat steps 5 and 6 while J >= K
Step 5 - Set LA[J+1] = LA[J]
Step 6 - Set J = J-1
Step 7 - Set LA[K] = ITEM
Step 8 - Stop

示例

由於 Java 中陣列的大小在插入操作後是固定的,因此插入操作後陣列的多餘元素將不會顯示。因此,如果要在陣列中間插入元素,為了顯示最後一個元素,需要建立一個大小為 n+1 的新陣列(其中 n 是當前陣列的大小),並將元素插入到其中,並顯示它,或者在列印陣列內容後單獨語句中列印最後一個元素。

public class InsertingElements {
   public static void main(String args[]) {
      int[] myArray = {10, 20, 30, 45, 96, 66};      
      int pos = 3;
      int data = 105;
      int j = myArray.length;
      int lastElement = myArray[j-1];
      
      for(int i = (j-2); i >= (pos-1); i--) {
    	  myArray[i+1] = myArray[i];
      }
      myArray[pos-1] = data;
      System.out.println("Contents of the array after insertion ::");
   
      for(int i = 0; i < myArray.length; i++) {
         System.out.print(myArray[i]+ ", ");
      }   
      System.out.print(lastElement);
   }
}

輸出

Contents of the array after insertion ::
10, 20, 105, 30, 45, 96, 66

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.Scanner;
import org.apache.commons.lang3.ArrayUtils;

public class InsertingElements {
   public static void main(String args[]) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter the number of elements needed :");
      int n = sc.nextInt();
      int[] myArray = new int[n];
      System.out.println("Enter the elements ::");
      
      for(int i = 0; i < n; i++) {
         myArray[i] = sc.nextInt();
      }        
      System.out.println("Enter the position to insert the element :");
      int pos = sc.nextInt();	  
      System.out.println("Enter the element:");
      int element = sc.nextInt();      
      int [] result = ArrayUtils.add(myArray, pos, element);      
      System.out.println("Contents of the array after insertion ::");   
      
      for(int i = 0; i < result.length; i++) {
         System.out.print(result[i]+ " ");
      }   
   }
}

輸出

Enter the number of elements needed :
5
Enter the elements ::
55
45
25
66
45
Enter the position to insert the element :
3
Enter the element:
404
Contents of the array after insertion ::
55 45 25 404 66 45
廣告

© . All rights reserved.