数组中插入元素
插入操作是在数组中插入一个或多个数据元素。根据需要,可以在数组的开头、结尾或任何给定索引处添加新元素。
算法
设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
广告