我们可以在Java列表中插入空值吗?
Solution
Yes, We can insert null values to a list easily using its add() method. In case of List implementation does not support null then it will throw NullPointerException.
Syntax
boolean add(E e)登录后复制
类型参数
E − 元素的运行时类型。
参数
e − 要追加到此列表的元素
返回值
返回true。
抛出
UnsupportedOperationException − 如果此列表不支持添加操作
ClassCastException − 如果指定元素的类阻止其添加到此列表中
NullPointerException − 如果指定的元素为null且此列表不允许null元素
IllegalArgumentException − 如果此元素的某些属性阻止其添加到此列表中
示例
以下示例演示如何使用add()方法向列表中插入null值。
package com.tutorialspoint; import java.util.ArrayList; import java.util.List; public class CollectionsDemo { public static void main(String[] args) { // Create a list object List list = new ArrayList(); // add elements to the list list.add("A"); list.add(null); list.add("B"); list.add(null); list.add("C"); // print the list System.out.println(list); } }登录后复制