如何在 Java 中向列表添加元素?

javaobject oriented programmingprogramming更新于 2025/1/2 3:24:17

我们可以使用 List 的 add() 方法将元素添加到列表中。

1. 使用不带索引的 add() 方法。

boolean add(E e)

将指定元素附加到此列表的末尾(可选操作)。

参数

  • e − 要附加到此列表的元素。

返回

True(由 Collection.add(E) 指定)。

抛出

  • UnsupportedOperationException −如果此列表不支持添加操作。

  • ClassCastException − 如果指定元素的类阻止将其添加到此列表。

  • NullPointerException − 如果指定元素为空,并且此列表不允许空元素。

  • IllegalArgumentException − 如果此元素的某些属性阻止将其添加到此列表。

2. 使用带有索引参数的 add() 在特定位置添加元素。

void add(int index, E element)

将指定元素插入此列表的指定位置(可选操作)。将当前位于该位置的元素(如果有)和任何后续元素向右移动(在其索引中加一)。

参数

  • index − 要插入指定元素的索引。

  • element − 要插入的元素。

抛出

  • UnsupportedOperationException − 如果此列表不支持添加操作。

  • 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)

相关文章


有用资源