为什么我无法在Java 8中继续使用带有Collections#forEach的标签?

问题描述 投票:3回答:1

编译后没有任何错误:

class App {
    boolean b;
    boolean c;

    void foo(List<Integer> ints) {
        myLabel:
        for (Integer i : ints) {
            while (!b) {
                if (c) {
                    continue myLabel;
                }
            }
        };
    }
}

但如果我修改foo如下:

void foo(List<Integer> ints) {
    myLabel:
    ints.forEach(integer -> {
        while (!b) {
            if (c) {
                continue myLabel;
            }
        }
    });
}

我得到Error:(17, 21) undefined label: myLabel

有什么区别?据我所知,新的forEach只是增强for循环的捷径?

java for-loop java-8 label
1个回答
5
投票

正如评论中所述,forEach只是一个方法调用。片段

myLabel: ints.forEach(integer -> ...);

是一个labeled statement

标识符语句标签与出现在标签语句中任何位置的breakcontinue语句(§14.15,§14.16)一起使用。

重复一下,带标签的语句是方法调用表达式。您的continue声明不在标签声明范围内。

你的continue statement是在lambda表达体内出现的while声明中。

带有标签continueIdentifier语句试图将控制转移到与其标签具有相同Identifier的封闭标签声明(第14.7节);该语句称为继续目标,然后立即结束当前迭代并开始新的迭代。

[...]

continue目标必须是whiledofor语句,否则会发生编译时错误。

continue语句必须引用直接封闭的方法,构造函数,初始值设定项或lambda体内的标签。没有非本地跳跃。如果在紧密封闭的方法,构造函数,初始化程序或lambda主体中没有使用Identifier作为其标签的带标签的语句包含continue语句,则会发生编译时错误。

由于在紧邻的lambda体中没有标记为while的标记(doformyLabel)语句,因此会出现编译时错误。

© www.soinside.com 2019 - 2024. All rights reserved.