java list 迭代 删除_java ArrayList迭代过程中删除

第一种迭代删除方式:

64ff1ccccaa644f07b3e4f766fbbd04c.png

第二种迭代删除方式:

fadde36884f96ae83eed8950b29379ef.png

第三种迭代删除:

f50b623ccdb626dfd738db5b8411c5b3.png

第四种迭代删除:

955b6b5648bbb0f1a6e4cabd80d5241e.png

第五种迭代删除:

3260db77c67f6d234da4fad93cdc89c4.png

第六种:

98f6c4a28ae3fdf19df3ff5ca5c73afc.png

ArrayList中remove()方法的机制,首先看源码:

85495f36d9e4498915dd9cafa606efa3.png

bb04a84e4fc19432b97d9dd6cce0ccb8.png

真正的删除操作在fastRemove(),首先定义一个新列表的长度newSize,其值为原列表长度减一 (newS-ze = size-1),然后将 索引 i 之后的数组元素全部向前进一位(System.arraycopy(es, i + 1, es, i, newSize - i)),接着最后一个原数组的最后一个元素置为null(es[size = newSize] = null;)。

所以使用for循环遍历删除的时候,每次循环时都要重新获取ArrayList的长度,并在删除元素之后将索引减1(i--)。

或者倒序删除。

迭代器删除:

private class Itr implements Iterator{int cursor; //index of next element to return//最后一个返回的元素的索引位置

int lastRet = -1; //index of last element returned; -1 if no such

int expectedModCount =modCount;//prevent creating a synthetic constructor

Itr() {}//当前迭代指示器是否指向列表末尾

public booleanhasNext() {return cursor !=size;

}

@SuppressWarnings("unchecked")publicE next() {

checkForComodification();int i =cursor;if (i >=size)throw newNoSuchElementException();

Object[] elementData= ArrayList.this.elementData;if (i >=elementData.length)throw newConcurrentModificationException();

cursor= i + 1; //迭代指示器指向下一个元素

return (E) elementData[lastRet =i];

}/*** 删除*/

public voidremove() {if (lastRet < 0)throw newIllegalStateException();

checkForComodification();try{//调用fastRemove删除元素

ArrayList.this.remove(lastRet);//迭代指示器指向被删除元素所在的索引位置

cursor =lastRet;

lastRet= -1;

expectedModCount=modCount;

}catch(IndexOutOfBoundsException ex) {throw newConcurrentModificationException();

}

}

@Overridepublic void forEachRemaining(Consumer super E>action) {

Objects.requireNonNull(action);final int size = ArrayList.this.size;int i =cursor;if (i =es.length)throw newConcurrentModificationException();for (; i < size && modCount == expectedModCount; i++)

action.accept(elementAt(es, i));//update once at end to reduce heap write traffic

cursor =i;

lastRet= i - 1;

checkForComodification();

}

}final voidcheckForComodification() {if (modCount !=expectedModCount)throw newConcurrentModificationException();

}

}

黄色部分是关键,删除元素后迭代指示器重新指向 “新” 元素,确保每一个元素都能被迭代指示器 “指” 过。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值