如何在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)
廣告