泛型类型参数在运行时不具备。检查这个:
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,它检查参数的类,从而解释了为什么强制元素类型为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