Java 如何在列表中的两个项目之间插入项目
我们可以使用其add()方法轻松地在数组列表的两个项目之间插入元素。
语法
void add(int index, E element)
在此列表的指定位置插入指定的元素(可选操作)。将该位置上当前的元素(如果有的话)和后续的元素向右移动(将其索引加一)。
类型参数
- E - 元素的运行时类型。
参数
- index - 要插入指定元素的索引位置。
-
e - 要插入到此列表中的元素。
抛出
-
UnsupportedOperationException - 如果此列表不支持添加操作。
-
ClassCastException - 如果指定元素的类阻止其被添加到此列表中。
-
NullPointerException - 如果指定元素为null并且此列表不允许null元素。
-
IllegalArgumentException - 如果某些属性阻止将此元素添加到此列表中。
-
IndexOutOfBoundsException - 如果索引超出范围(index < 0 || index > size())。
示例
以下示例显示了如何使用add()方法在列表中的项目之间插入元素。
package com.tutorialspoint;
import java.util.ArrayList;
import java.util.List;
public class CollectionsDemo {
public static void main(String[] args) {
// Create a list object
List<String> list = new ArrayList<>();
// add elements to the list
list.add("A");
list.add("B");
list.add("C");
// print the list
System.out.println(list);
list.add(1,"B");
System.out.println(list);
}
}
输出
这将产生以下结果 –
[A, C, D]
[A, B, C, D]