Java 怎样向列表中添加元素
我们可以使用List的add()方法向列表中添加元素。
1. 使用不带索引的add()方法
boolean add(E e)
将指定元素追加到此列表的末尾(可选操作)。
参数
- e - 要追加到此列表的元素。
返回值
True(由Collection.add(E)指定)。
抛出异常
- UnsupportedOperationException - 如果此列表不支持添加操作。
-
ClassCastException - 如果指定元素的类阻止其被添加到此列表。
-
NullPointerException - 如果指定元素为null,且此列表不允许空元素。
-
IllegalArgumentException - 如果此元素的某个属性阻止其被添加到此列表。
2. 使用带有索引参数的add()方法在特定位置添加元素
void add(int index, E element)
在此列表的指定位置插入指定的元素(可选操作)。将目前该位置的元素(如果有)和任何后续元素向右移动(将它们的索引加一)。
参数
- index - 要插入指定元素的索引。
-
element - 要插入的元素。
异常
-
UnsupportedOperationException - 如果此列表不支持添加操作。
-
ClassCastException - 如果指定元素的类阻止将其添加到此列表。
-
NullPointerException - 如果指定的元素为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) {
List<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
list.add(3);
list.add(5);
list.add(6);
System.out.println("List: " + list);
list.add(3, 4);
System.out.println("List: " + list);
try {
list.add(7, 7);
} catch(IndexOutOfBoundsException e) {
e.printStackTrace();
}
}
}
输出
这将产生以下结果:
List: [1, 2, 3, 5, 6]
List: [1, 2, 3, 4, 5, 6]
java.lang.IndexOutOfBoundsException: Index: 7, Size: 6
at java.base/java.util.ArrayList.rangeCheckForAdd(ArrayList.java:788)
at java.base/java.util.ArrayList.add(ArrayList.java:513)
at com.tutorialspoint.CollectionsDemo.main(CollectionsDemo.java:22)