Question 1
Is it irrelevant whether a List
(list of objects) or a List<String>
(list of Strings) is used in Groovy?
In the code example below, both lists end up being an ArrayList
(ArrayList of objects). Would have expected the second list to be an ArrayList<String>
(ArrayList of Strings).
Does Groovy lose the type information when the class is compiled and infer it when the compiled class is executed?
Example 1
List untypedList = ["a", "b", "c"]
List<String> typedList = ["a", "b", "c"]
println "Untyped list List: ${untypedList.getClass()}"
println "Typed list List<String>: ${typedList.getClass()}"
Output 1
Untyped list List: class java.util.ArrayList
Typed list List<String>: class java.util.ArrayList // Would have expected ArrayList<String>
Question 2
I would have expected the line typedList << new Integer(1)
in the example below to fail with an exception because I'm trying to put an int
into a list of Strings. Can anyone explain why I can add an int
to the String
-typed List
?
The output shows that it remains an Integer
, i.e. it's not on-the-fly converted to a String
"1".
Example 2
List untypedList = ["a", "b", "c"]
List<String> typedList = ["a", "b", "c"]
untypedList << new Integer(1)
typedList << new Integer(1) // Why does this work? Shouldn't an exception be thrown?
println "Types:"
println "Untyped list List: ${untypedList.getClass()}"
println "Typed list List<String>: ${typedList.getClass()}"
println "List contents:"
println untypedList
println typedList
println "Untyped list:"
untypedList.each { println it.getClass() }
println "Typed list:"
typedList.each { println it.getClass() }
Output 2
Types:
Untyped list List: class java.util.ArrayList
Typed list List<String>: class java.util.ArrayList
List contents:
[a, b, c, 1]
[a, b, c, 1]
Untyped list:
class java.lang.String
class java.lang.String
class java.lang.String
class java.lang.Integer
Typed list:
class java.lang.String
class java.lang.String
class java.lang.String
class java.lang.Integer