Java面试为何阿里强制要求不在foreach里执行删除操作

2022-07-21,,,,

小二听完就面露喜色,因为两年前,也就是 2021 年,他在《java 程序员进阶之路》专栏上的第 63 篇看到过这题😆。

ps:star 这种事,只能求,不求没效果,铁子们,《java 程序员进阶之路》在 github 上已经收获了 523 枚星标,小伙伴们赶紧去点点了,冲 600 star!

https://github.com/itwanger/tobebetterjavaer

为了镇楼,先搬一段英文来解释一下 fail-fast。

in systems design, a fail-fast system is one which immediately reports at its interface any condition that is likely to indicate a failure. fail-fast systems are usually designed to stop normal operation rather than attempt to continue a possibly flawed process. such designs often check the system's state at several points in an operation, so any failures can be detected early. the responsibility of a fail-fast module is detecting errors, then letting the next-highest level of the system handle them.

这段话的大致意思就是,fail-fast 是一种通用的系统设计思想,一旦检测到可能会发生错误,就立马抛出异常,程序将不再往下执行。

public void test(wanger wanger) {   
    if (wanger == null) {
        throw new runtimeexception("wanger 不能为空");
    }
    
    system.out.println(wanger.tostring());
}

一旦检测到 wanger 为 null,就立马抛出异常,让调用者来决定这种情况下该怎么处理,下一步 wanger.tostring() 就不会执行了——避免更严重的错误出现。

很多时候,我们会把 fail-fast 归类为 java 集合框架的一种错误检测机制,但其实 fail-fast 并不是 java 集合框架特有的机制。

之所以我们把 fail-fast 放在集合框架篇里介绍,是因为问题比较容易再现。

list<string> list = new arraylist<>();
list.add("沉默王二");
list.add("沉默王三");
list.add("一个文章真特么有趣的程序员");

for (string str : list) {
	if ("沉默王二".equals(str)) {
		list.remove(str);
	}
}

system.out.println(list);

这段代码看起来没有任何问题,但运行起来就报错了。

根据错误的堆栈信息,我们可以定位到 arraylist 的第 901 行代码。

final void checkforcomodification() {
    if (modcount != expectedmodcount)
        throw new concurrentmodificationexception();
}

也就是说,remove 的时候触发执行了 checkforcomodification 方法,该方法对 modcount 和 expectedmodcount 进行了比较,发现两者不等,就抛出了 concurrentmodificationexception 异常。

为什么会执行 checkforcomodification 方法呢?

是因为 for-each 本质上是个语法糖,底层是通过迭代器 iterator 配合 while 循环实现的,来看一下反编译后的字节码。

list<string> list = new arraylist();
list.add("沉默王二");
list.add("沉默王三");
list.add("一个文章真特么有趣的程序员");
iterator var2 = list.iterator();

while(var2.hasnext()) {
    string str = (string)var2.next();
    if ("沉默王二".equals(str)) {
        list.remove(str);
    }
}

system.out.println(list);

来看一下 arraylist 的 iterator 方法吧:

public iterator<e> iterator() {
    return new itr();
}

内部类 itr 实现了 iterator 接口。

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;

    itr() {}

    public boolean hasnext() {
        return cursor != size;
    }

    @suppresswarnings("unchecked")
    public e next() {
        checkforcomodification();
        int i = cursor;
        object[] elementdata = arraylist.this.elementdata;
        if (i >= elementdata.length)
            throw new concurrentmodificationexception();
        cursor = i + 1;
        return (e) elementdata[lastret = i];
    }
}

也就是说 new itr() 的时候 expectedmodcount 被赋值为 modcount,而 modcount 是 list 的一个成员变量,表示集合被修改的次数。由于 list 此前执行了 3 次 add 方法。

  • add 方法调用 ensurecapacityinternal 方法
  • ensurecapacityinternal 方法调用 ensureexplicitcapacity 方法
  • ensureexplicitcapacity 方法中会执行 modcount++

所以 modcount 的值在经过三次 add 后为 3,于是 new itr() 后 expectedmodcount 的值也为 3。

执行第一次循环时,发现“沉默王二”等于 str,于是执行 list.remove(str)

  • remove 方法调用 fastremove 方法
  • fastremove 方法中会执行 modcount++
private void fastremove(int index) {
    modcount++;
    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
}

modcount 的值变成了 4。

执行第二次循环时,会执行 itr 的 next 方法(string str = (string) var3.next();),next 方法就会调用 checkforcomodification 方法,此时 expectedmodcount 为 3,modcount 为 4,就只好抛出 concurrentmodificationexception 异常了。

那其实在阿里巴巴的 java 开发手册里也提到了,不要在 for-each 循环里进行元素的 remove/add 操作。remove 元素请使用 iterator 方式。

那原因其实就是我们上面分析的这些,出于 fail-fast 保护机制。

那该如何正确地删除元素呢?

1)remove 后 break

list<string> list = new arraylist<>();
list.add("沉默王二");
list.add("沉默王三");
list.add("一个文章真特么有趣的程序员");

for (string str : list) {
	if ("沉默王二".equals(str)) {
		list.remove(str);
		break;
	}
}

break 后循环就不再遍历了,意味着 iterator 的 next 方法不再执行了,也就意味着 checkforcomodification 方法不再执行了,所以异常也就不会抛出了。

但是呢,当 list 中有重复元素要删除的时候,break 就不合适了。

2)for 循环

list<string> list = new arraylist<>();
list.add("沉默王二");
list.add("沉默王三");
list.add("一个文章真特么有趣的程序员");
for (int i = 0, n = list.size(); i < n; i++) {
	string str = list.get(i);
	if ("沉默王二".equals(str)) {
		list.remove(str);
	}
}

for 循环虽然可以避开 fail-fast 保护机制,也就说 remove 元素后不再抛出异常;但是呢,这段程序在原则上是有问题的。为什么呢?

第一次循环的时候,i 为 0,list.size() 为 3,当执行完 remove 方法后,i 为 1,list.size() 却变成了 2,因为 list 的大小在 remove 后发生了变化,也就意味着“沉默王三”这个元素被跳过了。能明白吗?

remove 之前 list.get(1) 为“沉默王三”;但 remove 之后 list.get(1) 变成了“一个文章真特么有趣的程序员”,而 list.get(0) 变成了“沉默王三”。

3)使用 iterator

list<string> list = new arraylist<>();
list.add("沉默王二");
list.add("沉默王三");
list.add("一个文章真特么有趣的程序员");

iterator<string> itr = list.iterator();

while (itr.hasnext()) {
	string str = itr.next();
	if ("沉默王二".equals(str)) {
		itr.remove();
	}
}

为什么使用 iterator 的 remove 方法就可以避开 fail-fast 保护机制呢?看一下 remove 的源码就明白了。

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();
    }
}

删除完会执行 expectedmodcount = modcount,保证了 expectedmodcount 与 modcount 的同步。

简单地总结一下,fail-fast 是一种保护机制,可以通过 for-each 循环删除集合的元素的方式验证这种保护机制。

那也就是说,for-each 本质上是一种语法糖,遍历集合时很方面,但并不适合拿来操作集合中的元素(增删)。

这是《java 程序员进阶之路》专栏的第 63 篇。java 程序员进阶之路,风趣幽默、通俗易懂,对 java 初学者极度友好和舒适😘,内容包括但不限于 java 语法、java 集合框架、java io、java 并发编程、java 虚拟机等核心知识点。

https://github.com/itwanger/tobebetterjavaer

亮白版和暗黑版的 pdf 也准备好了呢,一起成为更好的 java 工程师,冲!

到此这篇关于java面试为何阿里强制要求不在foreach里执行删除操作的文章就介绍到这了,更多相关java 面试内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

《Java面试为何阿里强制要求不在foreach里执行删除操作.doc》

下载本文的Word格式文档,以方便收藏与打印。