这里有新鲜出炉的 Java 并发编程示例,程序狗速度看过来!
java 是一种可以撰写跨平台应用软件的面向对象的程序设计语言,是由 Sun Microsystems 公司于 1995 年 5 月推出的 Java 程序设计语言和 Java 平台(即 JavaEE(j2ee), JavaME(j2me), JavaSE(j2se))的总称。
这篇文章主要介绍了 Java 集合删除元素 ArrayList 实例详解的相关资料, 需要的朋友可以参考下
Java 集合删除元素 ArrayList 实例详解
AbstractCollection 集合类中有一个 remove 方法,该方法为了适配多种不同的集合,允许删除空的元素,看这部分代码的时候产生了疑问,为什么这里直接用 it.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;
- }
接下来,拿 ArrayList 为例子,进行说明。其继承结构如下图所示。并且,ArrayList 内部有其使用的 Iterator 的实现类。
编写一段测试代码:
- AbstractCollection < String > list = new ArrayList < >();
- list.add("a");
- list.add(null);
- list.add(null);
- Iterator < String > iter = list.iterator();
- while (iter.hasNext()) {
- if (iter.next() == null) {
- iter.remove();
- }
- }
- System.out.println(list);
关键点还是在于 iter.next() == null 这一行,next 的源码如下:
- 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];
- }
cusor 在这里表示的是遍历时的索引,在调用 next 方法的时候其实 cusor 已经指向了当前元素的下一个元素,而使用 lasrRet 来获取当前的索引上的数据并将其返回。
而 remove()方法中是通过 lastRet 的索引进行删除的。
- 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();
- }
- }
借助上文中提到的测试实例,可以进行每一步的推算。
1. 调用 next()方法,cursor 指向 0 号元素,i 被赋值为 cursor 的值,然后 cursor 被修改为 i+1,指向了 1 号元素,也就是 null 所在的位置, lastRet 被赋值为 0。
2. 调用 next()方法,cursor 指向了 1 号元素,赋值给 i, 然后 cursor 又通过 i+1 递增变为 2,lastRet 被赋值为 1
3. 执行删除,删除该集合 lastRet 上所代表的元素。删除完成后修改 cursor 指针同时使得 expectedModCount 和 modCount 保持一致避免 fastfail。
来源: http://www.phperz.com/article/17/1223/357361.html