【面试题精讲】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多平台发布

相关推荐
jyOverQ2 小时前
RabbitMQ 消息积压怎么办?Prefetch、消费者并发与扩容
分布式·后端·rabbitmq
东风破_10 小时前
从跨域到 WebSocket:前端跨域方案、SSE 与双向实时通信详解
前端·后端
行百里er11 小时前
Gateway 上别硬塞 MVC:DeferredImportSelector 看菜下锅
spring boot·后端·开源
名字还没想好☜11 小时前
Java 遍历时删元素抛 ConcurrentModificationException:fail-fast 原理与三种正确删法
后端
IT_陈寒12 小时前
React Hooks闭包陷阱差点让我加班到凌晨
前端·人工智能·后端
码事漫谈12 小时前
本体论,彻底懂
后端
创新技术阁13 小时前
FastapiAdmin 系统日志体系与核心配置参数详解
前端·后端·fastapi
掘金者阿豪13 小时前
SQL Server 迁到金仓,真正麻烦的不是数据,而是这些 T-SQL
后端
Kyrie_kk13 小时前
Java--IO--Path文件访问
java·后端
wxwx_bscxy32213 小时前
基于springboot宠物领养系统的设计与实现
数据库·spring boot·后端·spring·宠物