[英]Function .contains() not working in Groovy on expected way
I am trying to check if number is member of list by using Groovy programming language. 我试图通过使用Groovy编程语言检查数字是否是列表的成员。
I have this piece of code: 我有这段代码:
List<Long> list = [1, 2, 3]
Long number = 3
println(list.contains(number))
Expected output is true
, but the result I get is false
. 预期的输出是true
,但我得到的结果是false
。
Does anybody have an explanation? 有人有解释吗?
Generic type parameters don't feature at runtime. 通用类型参数在运行时不具备。 Check this: 检查一下:
List<Long> list = [1, 2, 3]
list.each{println it.getClass()}
Which prints: 哪个印刷品:
class java.lang.Integer
class java.lang.Integer
class java.lang.Integer
The true confusion is introduced by the bizarre behavior difference between .equals
and ==
implementations: .equals
和==
实现之间奇怪的行为差异引入了真正的混淆:
Long.valueOf(3).equals(Integer.valueOf(3))
===> false
Long.valueOf(3) == Integer.valueOf(3)
===> true
List.contains
seems to be using .equals
, which checks the class of the parameter, thus explaining why forcing element types to Long
resolves the problem. List.contains
似乎使用.equals
,它检查参数的类,从而解释为什么强制元素类型为Long
解决问题。
So, in the midst of this uncertainty, I think the only sure thing is that Groovy's ==
execution performs the most intuitive and predictable comparison. 因此,在这种不确定性中,我认为唯一确定的是Groovy的==
执行执行最直观和可预测的比较。 So I'd change the check to: 所以我将检查更改为:
boolean contains = list.grep{it == 3L} //sets value to true if matches at least 1
It helps when one doesn't have to be cognizant of data types linked to literals: 当一个人不必认识与文字链接的数据类型时,它会有所帮助:
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
Which works as anyone would want: 哪个像任何人想要的那样工作:
true
true
true
true
You should use the special literal values for longs: 1L instead of 1. 您应该使用long的特殊文字值:1L而不是1。
List<Long> list = [1L, 2L, 3L]
Long number = 3L
1 is an int. 1是int。 1L is a long. 1L很长。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.