List.contains for long values ​​does not return the expected value (groovy)

I played with Groovy and came across this interesting thing. Checking whether the list of lengths works with a specific number checks for integer values, but does not check long values.

​List<Long> list = [5, 7, 3]

println (5 in list) // true
println (5L in list) // false

int i = 5
long l = 5
println (i in list) // true
println (l in list) // false

Integer i2 = 5
Long l2 = 5
println (i2 in list) // true
println (l2 in list) // false

I ran this code at https://groovyconsole.appspot.com/ . This seems violated (or at least very controversial). I expect that there will be some problems with the implementation of List.contains and which comparison operator it uses? I can get around this, but I wonder if there is something that I am missing, or if this is actually intended behavior?

+4
source share
2 answers

, , . groovy ( ..), / .

, groovy groovy :

def list = [5, 7, 3]
// no type checking by default, so generics types does not matter due to type erasure
[...]

:

   List list = new ArrayList();
   list.add(5);
   list.add(7);
   list.add(3);

   System.out.println(list.contains(5)); // true
   System.out.println(list.contains(5L)); // false
   [...]

java ( -Xlint), .

groovy 2.0 / @groovy.transform.TypeChecked/@groovy.transform.CompileStatic ( ):

@groovy.transform.CompileStatic
class Test {
    static main(args) {
        List<Long> list = [5, 7, 3]

        println (5 in list) // true
        println (5L in list) // false

        int i = 5
        long l = 5
        println (i in list) // true
        println (l in list) // false

        Integer i2 = 5
        Long l2 = new Long(5)
        println (i2 in list) // true
        println (l2 in list) // false        
    }
}

, :

[Static type checking] - Incompatible generic argument types. Cannot assign java.util.List <java.lang.Integer> to: java.util.List <Long>
+1

, . :

List<Long> list = [5L, 7L, 3L]

, .

0

Source: https://habr.com/ru/post/1614707/


All Articles