函数 .contains() 无法按预期方式在 Groovy 中工作

Function .contains() not working in Groovy on expected way

我正在尝试使用 Groovy 编程语言检查数字是否是列表的成员。

我有这段代码:

List<Long> list = [1, 2, 3]
Long number = 3

println(list.contains(number))​

预期输出是true,但我得到的结果是false

有人有解释吗?

您应该使用长整型的特殊文字值:1L 而不是 1。

List<Long> list = [1L, 2L, 3L]
Long number = 3L

1 是一个整数。 1L是长的。

泛型类型参数在运行时不可用。检查这个:

List<Long> list = [1, 2, 3]
list.each{println it.getClass()}

打印:

class java.lang.Integer
class java.lang.Integer
class java.lang.Integer

真正的困惑是由 .equals== 实现之间奇怪的行为差异引起的:

Long.valueOf(3).equals(Integer.valueOf(3))
===> false
Long.valueOf(3) == Integer.valueOf(3)
===> true

List.contains 似乎在使用 .equals,它检查参数的 class,从而解释了为什么强制元素类型为 Long 可以解决问题。

因此,在这种不确定性之中,我认为唯一确定的是 Groovy 的 == 执行执行了最直观和可预测的比较。所以我将支票更改为:

boolean contains = list.grep{it == 3L} //sets value to true if matches at least 1

当不必了解与文字链接的数据类型时,它会有所帮助:

def ints = [1, 2, 3]
def longs = [1L, 2L, 3L]

boolean found1 = ints.grep{it == 3L}
boolean found2 = ints.grep{it == 3}
boolean found3 = longs.grep{it == 3L}
boolean found4 = longs.grep{it == 3}

println found1
println found2
println found3
println found4

任何人都会想要的:

true
true
true
true