
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 − 要追加到此列表的元素
立即学习“Java免费学习笔记(深入)”;
返回值
返回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);
}
} Output
This will produce the following result −
[A, null, B, null, C]











