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

使用java.util.List的containsAll()方法可能导致的问题

今天在偶然之间发现了一个bug,原因居然是使用了containsAll()方法,这个问题很简单,看以下代码就能发现很大的问题。

package collection;import java.util.ArrayList;
import java.util.List;/*** @author heyunlin* @version 1.0*/
public class ListExample {public static void main(String[] args) {List<Integer> list = new ArrayList<>();list.add(2);list.add(3);list.add(3);List<Integer> integerList = new ArrayList<>();integerList.add(3);integerList.add(3);integerList.add(3);System.out.println(list);System.out.println(integerList);System.out.println(list.containsAll(integerList));}}

上面的结果最后一行打印的是true,因为containsAll()方法的作用类似于遍历指定的集合c,通过contains()比较集合中每个元素,如果有元素不包含在当前的list对象中,就返回false,否则返回true,为了便于理解,写了以下伪代码

public interface List<E> extends Collection<E> {public boolean containsAll(Collection<?> c) {for (Object o : c) {if (!this.contains()) {return false;}}return true;}}

因此,文章给出的代码等价于

package collection;import java.util.ArrayList;
import java.util.List;/*** @author heyunlin* @version 1.0*/
public class ListExample {public static void main(String[] args) {List<Integer> list = new ArrayList<>();list.add(2);list.add(3);list.add(3);System.out.println(list);System.out.println(integerList);System.out.println(list.contains(3));}}

总结:这篇文章分享了一下项目中遇到的关于containsAll()方法使用时应该考虑到的问题,当比较的两个list中元素个数相同时,可以用equals()方法替代containsAll()方法使用,但是在使用之前需要对两个集合排序(因为List的源码里已经说明了,只有但集合元素的个数和顺序都一样才返回true)。

/*** Compares the specified object with this list for equality.  Returns* true if and only if the specified object is also a list, both* lists have the same size, and all corresponding pairs of elements in* the two lists are equal.  (Two elements e1 and* e2 are equal if (e1==null ? e2==null :* e1.equals(e2)).)  In other words, two lists are defined to be* equal if they contain the same elements in the same order.  This* definition ensures that the equals method works properly across* different implementations of the List interface.** @param o the object to be compared for equality with this list* @return true if the specified object is equal to this list*/
boolean equals(Object o);

好了,文章就分享到这里了,感谢阅读~

http://www.lryc.cn/news/112010.html

相关文章:

  • 在线文本转语音播放 (TTS)
  • OPTEE之ARM安全扩展
  • Vue [Day4]
  • google chrome 官方下载
  • Misc取证学习
  • vue打包到jar资源访问被shiro拦截
  • 选择排序(指针法)
  • 8.6 day07 休息+剑指offer
  • K8S系列文章 之 容器存储基础 Volume
  • 【CHI】架构介绍
  • hcip的ospf综合实验
  • AP5179 高端电流采样降压恒流驱动IC SOP8 LED车灯电源驱动
  • vue3+vite项目配置ESlint、pritter插件
  • K8S kubeadm搭建
  • Squeeze-and-Excitation Networks阅读笔记一
  • LabVIEW开发3D颈动脉图像边缘检测
  • python10.4.3
  • 系统架构设计高级技能 · 软件架构概念、架构风格、ABSD、架构复用、DSSA(一)【系统架构设计师】
  • Vue中,$forceUpdate()的使用
  • K8s中的Ingress
  • c++调用ffmpeg api录屏 并进行udp组播推流
  • war包方式安装linux和windows的geoserver
  • 安装CUDA与CUDNN与Pytorch(最新超级详细图文版本2023年8月最新)
  • 内存快照:宕机后,Redis如何实现快速恢复?RDB
  • Linux之 Ubuntu 安装常见服务 (二) Tomcat
  • docker 配置 Mysql主从集群
  • Layui实现OA会议系统之会议管理模块总合
  • fishing之踩坑篇捕获数据不齐全
  • ppt使用笔记
  • java中的hashmap和concurrenthashmap解析