0

我的 customList 类中有一个 remove 方法,它从我的 customList 对象中删除作为参数传递的对象,其中 contentInCustomList.equals(parameter) 并返回一个布尔值,指示是否删除了任何内容。
我正在尝试实现一个 remove all 方法,该方法接受一个集合,为集合的每个成员执行 remove 方法,将其作为参数传递,并返回一个布尔值,指示是否删除了任何内容。
为此,我将一个布尔值 (toReturn) 初始化为 false 并设置它,以便对于集合的每个成员,如果 remove(i) 或布尔值为真,我将其 (toReturn) 更改为 true。这样,如果 toReturn 已更改为 true,它将保持为 true。

public boolean removeAll(@NotNull Collection c) {
    boolean toReturn = false;
    c.forEach(i ->  toReturn = remove(i) || toReturn);
    return toReturn;
}

但是,当我尝试这样做时,它给了我一个错误,并且 intellliJ 告诉我将其转换为 AtomicBoolean:

public boolean removeAll(@NotNull Collection c) {
    AtomicBoolean toReturn = new AtomicBoolean(false);
    c.forEach(i -> toReturn.set(toReturn.get() || remove(i)));
    return toReturn.get();
}

为什么第一个不起作用,而第二个起作用?

4

0 回答 0