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

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

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

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

boolean add(E e)登录后复制

参数

  • e strong> - 要附加到此列表的元素。

返回

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

抛出

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

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

  • NullPointerException - 如果指定的元素为 null 并且此列表不允许 null 元素。

  • IllegalArgumentException - 如果此元素的某些属性阻止它不会被添加到此列表中。

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

void add(int index, E element)登录后复制

参数

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

抛出

  • UnsupportedOperationException - 如果不支持添加操作

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

  • NullPointerException - 如果指定的元素为 null 并且此列表不允许 null 元素。

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

  • IndexOutOfBoundsException - 如果索引超出范围( index size())。

示例

以下示例显示了 add() 方法的用法 - p>

package com.tutorialspoint; import java.util.ArrayList; import java.util.List; public class CollectionsDemo { public static void main(String[] args) { List 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(); } } }登录后复制