这段代码有点愚蠢,但它完全代表了问题。 两张地图不同,但总是返回真实。为什么会这样?
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()
}
}
答案 0 :(得分:2)
您正在从封闭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
}
或return a == b
与您的比较方法相同