
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.
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<String> 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);
}
}This will produce the following result −
[A, null, B, null, C]
以上就是我们可以在Java列表中插入空值吗?的详细内容,更多请关注php中文网其它相关文章!
java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号