groovy 中的布尔方法总是返回 true

Xel*_*ian 0 groovy equals map

这段代码有点愚蠢,但它完全代表了问题。这两个地图不同,但始终返回 true 。为什么会这样?

class SampleTest {

    private static boolean compare() {
        def a = [a:'one',b:'two']
        def b = [c:'three',d:'four']

        if(a.size()!=b.size()) {
            return false
        }
        a.each {
            if(!a.equals(b)){
                return false
            }
        }
        return true
    }
    static main(args) {
        println SampleTest.compare()
    }

}
Run Code Online (Sandbox Code Playgroud)

如果我添加额外的变量,那么一切正常:

class SampleTest {

    private static boolean compareArtifact() {
        boolean areEqual = true
        def a = [a:'one',b:'two']
        def b = [c:'three',d:'four']

        if(a.size()!=b.size()) {
            return false
        }
        a.each {
            if(!a.equals(b)){
                areEqual = false
            }
        }
        areEqual
    }
    static main(args) {
        println SampleTest.compareArtifact()
    }

}
Run Code Online (Sandbox Code Playgroud)

tim*_*tes 5

您正在从闭包内部调用 return each

这只会退出闭包,但不会从封闭函数中返回

您可以将其find用作早期终止循环,并检查结果是否为空

private static boolean compare() {
    def a = [a:'one',b:'two']
    def b = [c:'three',d:'four']

    if( a.size() != b.size() ) {
        return false
    }
    return a.find { a != b } == null
}
Run Code Online (Sandbox Code Playgroud)

return a == b与您的比较方法相同