JDK源码-Collection-remove()以及removeAll()
来源:互联网 发布:论文检测软件下载 编辑:程序博客网 时间:2024/06/06 20:43
remove()
再让我们来看一个处理与contains非常相似的方法,那就是remove()方法。源码如下:
public boolean remove(Object o) { Iterator<E> it = iterator(); if (o==null) { while (it.hasNext()) { if (it.next()==null) { it.remove(); return true; } } } else { while (it.hasNext()) { if (o.equals(it.next())) { it.remove(); return true; } } } return false;}
这块处理其实都是采用的迭代,Collection继承了Iterator,当然还有很多类继承了Collection,并对他的方法进行了重写。我们先了解父类的方法之后,后面我们会对个各子类中方法进行介绍。
removeAll()
直接看源码:
public boolean removeAll(Collection<?> c) { Objects.requireNonNull(c); boolean modified = false; Iterator<?> it = iterator(); while (it.hasNext()) { if (c.contains(it.next())) { it.remove(); modified = true; } } return modified; }
和containsAll原理一样,通过迭代来的,只要对象包含在collection中就remove掉这个对象。之后就返回值定义成true。
细心的人会发现,remove这个方法全部用的迭代(Iterator),
1.为什么不用for循环呢?
因为如果collection有下标,例如list(i),你一边remove,list的下标也是会发生变化的,所以,remove不用for会出错的。
2.为什么不用foreach?
没有为什么,人家就是选择了这个而已,别想太多。foreach循环就是用的iterator,foreach循环编译后还是被转成了iterator。
阅读全文
0 0
- JDK源码-Collection-remove()以及removeAll()
- JDK源码-Collection-contains()以及containsAll()
- JDK源码-Collection-add()以及addAll()
- ArrayList的方法:remove(object o) 、remove(int index)、removeAll(Collection c)时间复杂度的比较
- JDK源码-Collection-isEmpty
- JDK源码-Collection-clear()
- JDK源码-Collection-toString()
- Collection.removeAll 在 JDK 1.6 和 JDK 1.7 上不同的表现
- JAVA REMOVE REMOVEALL
- jdk源码之Collection接口
- JDK源码阅读-1-Collection
- jdk源码分析之Collection
- Java 集合之List 集合的删除方法顺序分析以及remove和removeAll区别
- JDK源码阅读之Collection分析
- JDK源码阅读之Collection集合接口
- JDK源码阅读——Collection
- 【JDK源码阅读1-util】Collection
- 【JDK源码阅读2-util】Collection-List
- OpenBSD新版将增加KARL功能:重启换内核
- (递推)折线分割平面--HDOJ
- mac实用软件
- 读取PCD文件
- 品尼高Pinnacle Studio 18下载 中文免费版
- JDK源码-Collection-remove()以及removeAll()
- HDU-1272 小希的迷宫
- Google着手与 Open AI 合作预防人工智能暴走
- 快速入门shell脚本编写(三)
- linux 部署多个Tomcat
- 使用ajax实现二级联动
- unity 2D中的向着鼠标点击方向进行射击
- Hadoop学习日志之序列化和反序列化
- Quartz定时任务调度