【面试题精讲】ArrayList 可以添加 null 值吗

有的时候博客内容会有变动,首发博客是最新的,其他博客地址可能会未同步,认准https://blog.zysicyj.top

首发博客地址

面试题手册

系列文章地址


ArrayList 是 Java 中的一个动态数组,可以存储任意类型的对象。在 ArrayList 中是可以添加 null 值的。

下面是一个示例代码:

java 复制代码
import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<>();
        
        list.add(null);
        list.add("Hello");
        list.add(null);
        
        System.out.println(list); // 输出:[null, Hello, null]
    }
}

在上述代码中,我们创建了一个 ArrayList 对象,并向其中添加了三个元素,包括两个 null 值和一个字符串 "Hello"。最后打印输出整个 ArrayList 的内容。

需要注意的是,在使用 ArrayList 存储 null 值时,要确保 ArrayList 的泛型类型允许为 null。例如,如果声明 ArrayList<int> 这样的列表,则无法将 null 添加到该列表中,因为 int 类型不允许为 null。

总结:

  • ArrayList 可以添加 null 值
  • 在使用 ArrayList 存储 null 值时,要确保 ArrayList 的泛型类型允许为 null。

本文由mdnice多平台发布

相关推荐
哎呦没25 分钟前
大学生就业招聘:Spring Boot系统的架构分析
java·spring boot·后端
_.Switch44 分钟前
Python Web 应用中的 API 网关集成与优化
开发语言·前端·后端·python·架构·log4j
杨哥带你写代码2 小时前
足球青训俱乐部管理:Spring Boot技术驱动
java·spring boot·后端
AskHarries3 小时前
读《show your work》的一点感悟
后端
A尘埃3 小时前
SpringBoot的数据访问
java·spring boot·后端
yang-23073 小时前
端口冲突的解决方案以及SpringBoot自动检测可用端口demo
java·spring boot·后端
Marst Code3 小时前
(Django)初步使用
后端·python·django
代码之光_19803 小时前
SpringBoot校园资料分享平台:设计与实现
java·spring boot·后端
编程老船长3 小时前
第26章 Java操作Mongodb实现数据持久化
数据库·后端·mongodb
IT果果日记4 小时前
DataX+Crontab实现多任务顺序定时同步
后端