当前位置: 首页 > news >正文

【Java 集合】Collections 空列表细节处理

问题

如下代码,虽然定义为非空 NonNull,但依然会返回空对象,导致调用侧被检测为空引用。

实际上不是Collections的问题是三目运算符返回了null对象。

import java.util.Collections;@NonNullprivate List<String> getInfo() {IccRecords iccRecords = mPhone.getIccRecords();if(iccRecords != null) {//省略逻辑String[] simSpdi = iccRecords.getServiceProviderDisplayInformation();return simSpdi != null ? Arrays.asList(simSpdi) : null; //根因是这里返回null}return Collections.EMPTY_LIST;}

源码案例

frameworks/opt/telephony/src/java/com/android/internal/telephony/cdnr/CarrierDisplayNameResolver.java

    @NonNullprivate List<String> getEfSpdi() {for (int i = 0; i < mEf.size(); i++) {if (mEf.valueAt(i).getServiceProviderDisplayInformation() != null) {return mEf.valueAt(i).getServiceProviderDisplayInformation();}}return Collections.EMPTY_LIST;}@NonNullprivate String getEfSpn() {for (int i = 0; i < mEf.size(); i++) {if (!TextUtils.isEmpty(mEf.valueAt(i).getServiceProviderName())) {return mEf.valueAt(i).getServiceProviderName();}}return "";}@NonNullprivate List<OperatorPlmnInfo> getEfOpl() {for (int i = 0; i < mEf.size(); i++) {if (mEf.valueAt(i).getOperatorPlmnList() != null) {return mEf.valueAt(i).getOperatorPlmnList();}}return Collections.EMPTY_LIST;}@NonNullprivate List<PlmnNetworkName> getEfPnn() {for (int i = 0; i < mEf.size(); i++) {if (mEf.valueAt(i).getPlmnNetworkNameList() != null) {return mEf.valueAt(i).getPlmnNetworkNameList();}}return Collections.EMPTY_LIST;}

代码解析

注意Collection和Collections是不同的。

  • libcore/ojluni/src/main/java/java/util/Collections.java 工具类
  • libcore/ojluni/src/main/java/java/util/Collection.java 接口

Collections中定义了内部类EmptyList,在静态List常量EMPTY_LIST(immutable不可变列表)初始化时会new一个没有指定类型的EmptyList。

public class Collections {/*** The empty list (immutable).  This list is serializable.** @see #emptyList()*/@SuppressWarnings("rawtypes")public static final List EMPTY_LIST = new EmptyList<>();/*** Returns an empty list (immutable).  This list is serializable.** <p>This example illustrates the type-safe way to obtain an empty list:* <pre>*     List&lt;String&gt; s = Collections.emptyList();* </pre>** @implNote* Implementations of this method need not create a separate {@code List}* object for each call.   Using this method is likely to have comparable* cost to using the like-named field.  (Unlike this method, the field does* not provide type safety.)** @param <T> type of elements, if there were any, in the list* @return an empty immutable list** @see #EMPTY_LIST* @since 1.5*/@SuppressWarnings("unchecked")public static final <T> List<T> emptyList() {return (List<T>) EMPTY_LIST;}/*** @serial include*/private static class EmptyList<E>extends AbstractList<E>implements RandomAccess, Serializable {@java.io.Serialprivate static final long serialVersionUID = 8842843931221139166L;public Iterator<E> iterator() {return emptyIterator();}public ListIterator<E> listIterator() {return emptyListIterator();}// Preserves singleton property@java.io.Serialprivate Object readResolve() {return EMPTY_LIST;}}}

解决方案

将 Collections.EMPTY_LIST 替换成 Collections.emptyList()。

虽然它们都可以用于表示一个空的不可变列表,但 Collections.emptyList() 是更优先的选择,因为它提供了类型安全性和更好的代码可读性。

附:Collections 源码

一些值得学习的语法,Android 扩展的排序跟Java 集合原生排序的实现差异

libcore/ojluni/src/main/java/java/util/Collections.java

import dalvik.system.VMRuntime;/*** This class consists exclusively of static methods that operate on or return* collections.  It contains polymorphic algorithms that operate on* collections, "wrappers", which return a new collection backed by a* specified collection, and a few other odds and ends.** <p>The methods of this class all throw a {@code NullPointerException}* if the collections or class objects provided to them are null.** <p>The documentation for the polymorphic algorithms contained in this class* generally includes a brief description of the <i>implementation</i>.  Such* descriptions should be regarded as <i>implementation notes</i>, rather than* parts of the <i>specification</i>.  Implementors should feel free to* substitute other algorithms, so long as the specification itself is adhered* to.  (For example, the algorithm used by {@code sort} does not have to be* a mergesort, but it does have to be <i>stable</i>.)** <p>The "destructive" algorithms contained in this class, that is, the* algorithms that modify the collection on which they operate, are specified* to throw {@code UnsupportedOperationException} if the collection does not* support the appropriate mutation primitive(s), such as the {@code set}* method.  These algorithms may, but are not required to, throw this* exception if an invocation would have no effect on the collection.  For* example, invoking the {@code sort} method on an unmodifiable list that is* already sorted may or may not throw {@code UnsupportedOperationException}.** <p>This class is a member of the* <a href="{@docRoot}/java.base/java/util/package-summary.html#CollectionsFramework">* Java Collections Framework</a>.** @author  Josh Bloch* @author  Neal Gafter* @see     Collection* @see     Set* @see     List* @see     Map* @since   1.2*/public class Collections {// Suppresses default constructor, ensuring non-instantiability.private Collections() {}// Algorithms// Android-added: List.sort() vs. Collections.sort() app compat.// Added a warning in the documentation.// Collections.sort() calls List.sort() for apps targeting API version >= 26// (Android Oreo) but the other way around for app targeting <= 25 (Nougat)./*** Sorts the specified list into ascending order, according to the* {@linkplain Comparable natural ordering} of its elements.* All elements in the list must implement the {@link Comparable}* interface.  Furthermore, all elements in the list must be* <i>mutually comparable</i> (that is, {@code e1.compareTo(e2)}* must not throw a {@code ClassCastException} for any elements* {@code e1} and {@code e2} in the list).** <p>This sort is guaranteed to be <i>stable</i>:  equal elements will* not be reordered as a result of the sort.** <p>The specified list must be modifiable, but need not be resizable.** @implNote* This implementation defers to the {@link List#sort(Comparator)}* method using the specified list and a {@code null} comparator.* Do not call this method from {@code List.sort()} since that can lead* to infinite recursion. Apps targeting APIs {@code <= 25} observe* backwards compatibility behavior where this method was implemented* on top of {@link List#toArray()}, {@link ListIterator#next()} and* {@link ListIterator#set(Object)}.** @param  <T> the class of the objects in the list* @param  list the list to be sorted.* @throws ClassCastException if the list contains elements that are not*         <i>mutually comparable</i> (for example, strings and integers).* @throws UnsupportedOperationException if the specified list's*         list-iterator does not support the {@code set} operation.* @throws IllegalArgumentException (optional) if the implementation*         detects that the natural ordering of the list elements is*         found to violate the {@link Comparable} contract* @see List#sort(Comparator)*/public static <T extends Comparable<? super T>> void sort(List<T> list) {// Android-changed: List.sort() vs. Collections.sort() app compat.// Call sort(list, null) here to be consistent with that method's// (changed on Android) behavior.// list.sort(null);sort(list, null);}}

相关文章:

【Java 集合】Collections 空列表细节处理

问题 如下代码&#xff0c;虽然定义为非空 NonNull&#xff0c;但依然会返回空对象&#xff0c;导致调用侧被检测为空引用。 实际上不是Collections的问题是三目运算符返回了null对象。 import java.util.Collections;NonNullprivate List<String> getInfo() {IccReco…...

大数据实验4-HBase

一、实验目的 阐述HBase在Hadoop体系结构中的角色&#xff1b;能够掌握HBase的安装和配置方法熟练使用HBase操作常用的Shell命令&#xff1b; 二、实验要求 学习HBase的安装步骤&#xff0c;并掌握HBase的基本操作命令的使用&#xff1b; 三、实验平台 操作系统&#xff1…...

deepin系统下载pnpm cnpm等报错

deepin系统下载pnpm cnpm等报错 npm ERR! request to https://registry.npm.taobao.org/pnpm failed, reason: certificate has expired 报错提示证书过期&#xff0c;执行以下命令 npm config set registry https://registry.npmmirror.com下载pnpm npm install pnpm -g查…...

#Js篇:JSON.stringify 和 JSON.parse用法和传参

JSON.stringify 和 JSON.parse 1. JSON.stringify JSON.stringify 方法将一个 JavaScript 对象或数组转换为 JSON 字符串。 基本用法 const obj { name: "Alice", age: 25 }; const jsonString JSON.stringify(obj); console.log(jsonString); // 输出: {"…...

c#通过网上AI大模型实现对话功能

目录 基础使用给大模型额外提供函数能力用Microsoft.Extensions.AI库实现用json格式回答 基础使用 https://siliconflow.cn/网站有些免费的大模型可以使用&#xff0c;去注册个账户&#xff0c;拿到apikey 引用 nuget Microsoft.Extensions.AI.OpenAI using Microsoft.Extensi…...

pymysql模块

1.pymysql基本使用 打开数据库连接,使用cursor()方法获取操作游标执行SQL语句 获取命令执行的查询结果 1.1 打开数据库连接 # 打开数据库连接 db pymysql.connect(host127.0.0.1,userroot,port3306,password"123",databasedb5) 1.2 使用cursor()方法获取操作游…...

WPF-模板和样式

在 WPF&#xff08;Windows Presentation Foundation&#xff09;中&#xff0c;模板是一种强大的机制&#xff0c;用于定义控件的外观。它允许你将控件的逻辑&#xff08;功能&#xff09;和外观&#xff08;UI&#xff09;分离开来。例如&#xff0c;一个按钮控件&#xff0c…...

网络编程 day1.2~day2——TCP和UDP的通信基础(TCP)

笔记脑图 作业&#xff1a; 1、将虚拟机调整到桥接模式联网。 2、TCP客户端服务器实现一遍。 服务器 #include <stdio.h> #include <string.h> #include <myhead.h> #define IP "192.168.60.44" #define PORT 6666 #define BACKLOG 20 int mai…...

element ui table 每行不同状态

table 每行定义值 tableData: [ { name: ,type:,location:, ziduan:,createtype:,ziduanvalue:,checkAll:true,checkedCities: [空, null, str随机, int随机],isIndeterminate: true,table_id:single,downloaddisabled:true,deldisabled:true} ], table c…...

力扣--LRC 142.训练计划IV

题目 给定两个以 有序链表 形式记录的训练计划 l1、l2&#xff0c;分别记录了两套核心肌群训练项目编号&#xff0c;请合并这两个训练计划&#xff0c;按训练项目编号 升序 记录于链表并返回。 注意&#xff1a;新链表是通过拼接给定的两个链表的所有节点组成的。 示例 1&am…...

windows下,用CMake编译qt项目,出现错误By not providing “FindQt5.cmake“...

开发环境&#xff1a;windows10 qt5.14&#xff0c; 编译器msvc2017x64&#xff0c;CMake3.30&#xff1b; 现象&#xff1a; CMakeList文件里&#xff0c;如有find_package(Qt5 COMPONENTS Widgets REQUIRED) target_link_libraries(dis_lib PRIVATE Qt5::Widgets) 用CMak…...

【element-tiptap】Tiptap编辑器核心概念----结构篇

core-concepts 前言&#xff1a;这篇文章来介绍一下 Tiptap 编辑器的一些核心概念 &#xff08;一&#xff09;结构 1、 Schemas 定义文档组成方式。一个文档就是标题、段落以及其他的节点组成的一棵树。 每一个 ProseMirror 的文档都有一个与之相关联的 schema&#xff0c;…...

半导体工艺与制造篇3 离子注入

离子注入工艺 一般掺杂的杂质类别&#xff0c;包括:提供载流子的施主杂质和受主杂质;产生复合中心的重金属杂质 离子注入往往需要生成井well&#xff0c;其中井的定义&#xff1a;晶圆与杂质之间形成的扩散层或杂质与杂质之间形成的扩散层 离子注入的目的&#xff1a;用掺杂改…...

利用开源的低代码表单设计器FcDesigner高效管理和渲染复杂表单结构

FcDesigner 是一个强大的开源低代码表单设计器组件&#xff0c;支持快速拖拽生成表单。提供丰富的自定义及扩展功能&#xff0c;FcDesigner支持多语言环境&#xff0c;并允许开发者进行二次开发。通过将表单设计输出为JSON格式&#xff0c;再通过渲染器进行加载&#xff0c;实现…...

淘宝 NPM 镜像源

npm i vant/weapp -S --production npm config set registry https://registry.npmmirror.com 要在淘宝 NPM 镜像站下载项目或依赖&#xff0c;你可以按照以下步骤操作&#xff1a; 1. 设置淘宝 NPM 镜像源 首先&#xff0c;你需要设置淘宝 NPM 镜像源以加速下载。可以通过…...

i春秋-GetFlag(md5加密,字符串比较绕过)

练习平台地址 竞赛中心 题目描述 题目内容 你好&#xff0c;单身狗&#xff0c;这是一个迷你文件管理器&#xff0c;你可以登录和下载文件&#xff0c;甚至得到旗帜 点击登录 发现capture需要满足条件substr(md5(captcha), 0, 6)xxxxxx 编写python脚本破解验证码 import has…...

SpringBoot中设置超时30分钟自动删除元素的List和Map

简介 在 Spring Boot 中&#xff0c;你可以使用多种方法来实现自动删除超时元素的 List 或 Map。以下是两种常见的方式&#xff1a; 如果你需要简单的功能并且不介意引入外部依赖&#xff0c;可以选择 Guava Cache。如果你想要更灵活的控制&#xff0c;使用 Spring 的调度功能…...

入门车载以太网(6) -- XCP on Ethernet

目录 1.寻址方式 2.数据帧格式 3.特殊指令 4.使用实例 了解了SOME/IP之后&#xff0c;继续来看看车载以太网在汽车标定领域的应用。 在汽车标定领域XCP是非常重要的协议&#xff0c;咱们先来回顾下基础概念。 XCP全称Universal Measurement and Calibration Protocol&a…...

DAY4 网络编程(广播和多线程并发)

作业1&#xff1a; 1、将广播发送和接收端实现一遍&#xff0c;完成一个发送端发送信息&#xff0c;对应多个接收端接收信息实验。 send.c代码&#xff1a; #include <myhead.h> #define IP "192.168.61.255"//广播IP #define PORT 7777 int main(int argc, …...

C++个人复习(4)

C中为什么要引入make_shared,它有什么优点 1. 减少内存分配次数 使用 make_shared 时&#xff0c;内存分配只发生一次&#xff0c;它同时分配了对象和控制块&#xff08;用于管理引用计数等信息&#xff09;。而如果直接使用 new 创建对象并传递给 shared_ptr&#xff0c;则会…...

(LeetCode 每日一题) 3442. 奇偶频次间的最大差值 I (哈希、字符串)

题目&#xff1a;3442. 奇偶频次间的最大差值 I 思路 &#xff1a;哈希&#xff0c;时间复杂度0(n)。 用哈希表来记录每个字符串中字符的分布情况&#xff0c;哈希表这里用数组即可实现。 C版本&#xff1a; class Solution { public:int maxDifference(string s) {int a[26]…...

Lombok 的 @Data 注解失效,未生成 getter/setter 方法引发的HTTP 406 错误

HTTP 状态码 406 (Not Acceptable) 和 500 (Internal Server Error) 是两类完全不同的错误&#xff0c;它们的含义、原因和解决方法都有显著区别。以下是详细对比&#xff1a; 1. HTTP 406 (Not Acceptable) 含义&#xff1a; 客户端请求的内容类型与服务器支持的内容类型不匹…...

利用ngx_stream_return_module构建简易 TCP/UDP 响应网关

一、模块概述 ngx_stream_return_module 提供了一个极简的指令&#xff1a; return <value>;在收到客户端连接后&#xff0c;立即将 <value> 写回并关闭连接。<value> 支持内嵌文本和内置变量&#xff08;如 $time_iso8601、$remote_addr 等&#xff09;&a…...

Spring Boot 实现流式响应(兼容 2.7.x)

在实际开发中&#xff0c;我们可能会遇到一些流式数据处理的场景&#xff0c;比如接收来自上游接口的 Server-Sent Events&#xff08;SSE&#xff09; 或 流式 JSON 内容&#xff0c;并将其原样中转给前端页面或客户端。这种情况下&#xff0c;传统的 RestTemplate 缓存机制会…...

AtCoder 第409​场初级竞赛 A~E题解

A Conflict 【题目链接】 原题链接&#xff1a;A - Conflict 【考点】 枚举 【题目大意】 找到是否有两人都想要的物品。 【解析】 遍历两端字符串&#xff0c;只有在同时为 o 时输出 Yes 并结束程序&#xff0c;否则输出 No。 【难度】 GESP三级 【代码参考】 #i…...

抖音增长新引擎:品融电商,一站式全案代运营领跑者

抖音增长新引擎&#xff1a;品融电商&#xff0c;一站式全案代运营领跑者 在抖音这个日活超7亿的流量汪洋中&#xff0c;品牌如何破浪前行&#xff1f;自建团队成本高、效果难控&#xff1b;碎片化运营又难成合力——这正是许多企业面临的增长困局。品融电商以「抖音全案代运营…...

[10-3]软件I2C读写MPU6050 江协科技学习笔记(16个知识点)

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16...

SpringBoot+uniapp 的 Champion 俱乐部微信小程序设计与实现,论文初版实现

摘要 本论文旨在设计并实现基于 SpringBoot 和 uniapp 的 Champion 俱乐部微信小程序&#xff0c;以满足俱乐部线上活动推广、会员管理、社交互动等需求。通过 SpringBoot 搭建后端服务&#xff0c;提供稳定高效的数据处理与业务逻辑支持&#xff1b;利用 uniapp 实现跨平台前…...

稳定币的深度剖析与展望

一、引言 在当今数字化浪潮席卷全球的时代&#xff0c;加密货币作为一种新兴的金融现象&#xff0c;正以前所未有的速度改变着我们对传统货币和金融体系的认知。然而&#xff0c;加密货币市场的高度波动性却成为了其广泛应用和普及的一大障碍。在这样的背景下&#xff0c;稳定…...

AGain DB和倍数增益的关系

我在设置一款索尼CMOS芯片时&#xff0c;Again增益0db变化为6DB&#xff0c;画面的变化只有2倍DN的增益&#xff0c;比如10变为20。 这与dB和线性增益的关系以及传感器处理流程有关。以下是具体原因分析&#xff1a; 1. dB与线性增益的换算关系 6dB对应的理论线性增益应为&…...