Java循环删除集合多个元素的正确打开方式
首先说下不正确的打开方式:
第一:使用for循环删除集合的元素,示例代码如下
ArrayList<String> list = new ArrayList<String>(Arrays.asList("a", "b", "c", "d"));
for (int i = 0; i < list.size(); i++) {
list.remove(i);
}
System.out.println(list);
结果输出为:
[b, d]
解说开始:
首先看下源码:
public E remove(int index) {
rangeCheck(index);
modCount++;
E oldValue = elementData(index);
int numMoved = size - index - 1;
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
elementData[--size] = null; // clear to let GC do its work
return oldValue;
}
解释:第一次进for循环,i=0 ,调用remove方法删除第一位的元素, 集合大小收缩,第一次删除完成后,list变成【b,c,d】;再次循环,i=1,调用remove方法删除了c 集合大小再次收缩,list变成【b,d】;再次循环,i=2,不符合条件,循环结束
第二:使用foreach循环删除元素,示例代码如下
ArrayList<String> list = new ArrayList<String>(Arrays.asList("a", "b", "c", "d"));
for (String s : list) {
if (s.equals("b"))
list.remove(s);
}
System.out.println(list);
结果:这段代码居然抛出了异常 java.util.ConcurrentModificationException。
解说开始:
首先看下源代码:
public Iterator<E> iterator() {
return new Itr();
}
/**
* An optimized version of AbstractList.Itr
*/
private class Itr implements Iterator<E> {
int cursor; // index of next element to return
int lastRet = -1; // index of last element returned; -1 if no such
int expectedModCount = modCount;
public boolean hasNext() {
return cursor != size;
}
@SuppressWarnings("unchecked")
public E next() {
checkForComodification();
int i = cursor;
if (i >= size)
throw new NoSuchElementException();
Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length)
throw new ConcurrentModificationException();
cursor = i + 1;
return (E) elementData[lastRet = i];
}
public void remove() {
if (lastRet < 0)
throw new IllegalStateException();
checkForComodification();
try {
ArrayList.this.remove(lastRet);
cursor = lastRet;
lastRet = -1;
expectedModCount = modCount;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}
解释:在Java中的foreach循环的工作原理就像一个iterator。
so,接下来说下正确的打开方式——
ArrayList<Integer> a=new ArrayList<Integer>(15);
a.add(222);
a.add(3);
a.add(333);
a.add(000);
a.add(333);
a.add(4); for(int s=a.size()-1;s>=0;s--){
if(a.get(s).intValue()==333){
a.remove(s);
}
}
privatevoid screenBlackNameList(List<SharedBoardSmsWrapper> source, List<BlackNameListModel> blackNameList){
Iterator<SharedBoardSmsWrapper> sourceIt=source.iterator();
while(sourceIt.hasNext()){
SharedBoardSmsWrapper tmpSharedBoardSmsWrapper=sourceIt.next();
Iterator<BlackNameListModel> blackNameListIt=blackNameList.iterator();
while(blackNameListIt.hasNext()){
BlackNameListModel tmpBlackNameListModel=blackNameListIt.next();
if(tmpSharedBoardSmsWrapper.getSource().equals(tmpBlackNameListModel.getSource())){
sourceIt.remove();
break;
}
}
}
}
Java循环删除集合多个元素的正确打开方式的更多相关文章
- (CSDN 迁移) JAVA循环删除List的某个元素
若列表中只可能存在一个则可以用简单的循环删除,不多说. 若列表中可能存在多个,尤其是可能有多个连续的需要删除,用简单循环有可能发生异常. 需要使用迭代器(Iterator),两种具体实现: 逻辑上是一 ...
- for循环删除集合陷阱
首先看下面的代码: import java.util.LinkedList;import java.util.List; public class DeleteCollection { ...
- 集合赋值及for循环删除符合条件的元素
一.Java语言中ArrayList对象能直接赋值给另一个ArrayList对象吗? https://zhidao.baidu.com/question/399214655.html ArrayLis ...
- ArrayList之foreach循环删除倒数第二个元素,不触发fail-fast机制
今天一朋友问了个问题,对于如下一段代码,运行后会有怎样的结果? public class ArrayListTest { public static void main(String[] args) ...
- Python笔记:用for循环删除列表中的元素
for运行过程中会有一个指针来记录当前循环的元素是哪一个,一开始这个指针指向第0个元素,然后获取它,接着删除第0个元素,这时候,原来是第1个的元素会变成第0个,当指针向后移动一次,指向了现在第1个元素 ...
- python循环删除list中的元素
直接上例子: a = [1,2,3,4,5,6] for i in a: a.remove(i) print(a) 返回:[2, 4, 6] 循环a,想删除a的所有元素,但实际确有数据保留了下来,这是 ...
- Java思考——HashSet集合如何保证元素的唯一性也就是不包含重复元素?
首先将源码逐级找出来1.HashSet<String> hs=new HashSet<String>(); hs.add("hello"); ...
- C#实现在foreach中删除集合中的元素
List<string> str = new List<string>(); str.Add( "zs"); str.Add("ls") ...
- java的取出map里所有元素的两种方式
/* * 取出map元素的两种方式 */package com.map.test; import java.util.HashMap;import java.util.Iterator;import ...
随机推荐
- [linux系统]--spawn 用法
spawn与except组合可达到远程登录设备执行命令的作用 下面是登录设备的一段代码 #!/usr/bin/expect -f user=root host=1.1.1.1 password=roo ...
- SQL 语句调优 where 条件 数据类型 临时表 索引
基本原则 避免全表扫描 建立索引 尽量避免向客户端返回大数据量,若数据量过大,应该考虑相应需求是否合理 尽量避免大事务操作,提高系统并发能力 使用基于游标的方法或临时表方法之前,应先寻找基于集的解决方 ...
- 使用maven搭建SpringMVC项目环境
Window环境下用maven新建一个项目: mvn archetype:generate -DarchetypeCatalog=internal -DgroupId=cn-cisol -Dartif ...
- spring定时器配置
在此记录两种定时任务的配置: 一种是quart定时器: <1>配置xml文件(定时任务配置) <!--定时任务 --> <bean id="txfwBomc&q ...
- 使用AFNetWorking 实现以Basic Authentication方式获取access-token
由于服务器端对于调用API获取数据接口进行了限制,需要在调用API之前获取一个access-token,所以需要在iOS里实现获取这个access-token的功能. 服务器端是在ASP.NET中基于 ...
- ABAP代码编辑器设置--界线
ABAP编辑器每行允许的最大字符数: Utilities->Settings打开选项卡: 勾选:Downward-Compat.line Length(72) 设置后看到的效果: 设置步骤:
- word 常用宏代码
2008年05月25日 11:08 Sub autonew1()Dim 存在, a, i, j, strOn Error Resume NextFor j = 1 To ActiveDocument. ...
- getFragmentManager()和getSupportFragmentManager()
在Android开发中,少不了Fragment的运用.目前在实际运用中,有v-4包下支持的Fragment以及app包下的Fragment,这两个包下的FragmentManager获取方式有点区别, ...
- 6.Swift协议|扩展|访问权限|异常调试|类型转换|运算函数|ARC|类类型初试化器|值类型初始化器
1. 协议(Protocol):与OC之间唯一不同的是Swift中的协议不管是属性还时方法全部是必须实现的 /** protocol*/ protocol FullNamed { /** 计算属性申明 ...
- 合并文件夹里多个excel
Sub 合并当前目录下所有工作簿的全部工作表() Dim MyPath, MyName, AWbName Dim Wb As workbook, WbN As String Dim G As Long ...