groovy中的Boolean方法总是返回true

时间:2013-12-02 17:03:44

标签: map groovy equals

这段代码有点愚蠢,但它完全代表了问题。 两张地图不同,但总是返回真实。为什么会这样?

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

}

如果我添加其他变量,那么一切正常:

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

}

1 个答案:

答案 0 :(得分:2)

您正在从封闭each

中调用return

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

您可以使用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
}

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

相关问题