如何在Java中向列表添加元素?
我们可以使用List 的 add() 方法 向列表添加元素。
1. 使用不带索引的 add() 方法。
boolean add(E e)
将指定的元素追加到此列表的末尾(可选操作)。
参数
e − 要添加到此列表的元素。
返回值
True(如 Collection.add(E) 所指定)。
抛出异常
UnsupportedOperationException − 如果此列表不支持 add 操作。
ClassCastException − 如果指定元素的类阻止将其添加到此列表。
NullPointerException − 如果指定的元素为空,而此列表不允许空元素。
IllegalArgumentException − 如果此元素的某些属性阻止将其添加到此列表。
2. 使用带索引参数的 add() 方法在特定位置添加元素。
void add(int index, E element)
在此列表的指定位置插入指定的元素(可选操作)。将当前位于该位置的元素(如果有)以及任何后续元素向右移动(将其索引加一)。
参数
index − 要插入指定元素的索引。
element − 要插入的元素。
抛出异常
UnsupportedOperationException − 如果此列表不支持 add 操作。
ClassCastException − 如果指定元素的类阻止将其添加到此列表。
NullPointerException − 如果指定的元素为空,而此列表不允许空元素。
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)
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP