它是無關緊要是否List
(對象列表)或List<String>
(字符串列表)在Groovy中使用?
在下面的代碼示例中,兩個列表最終都是ArrayList
(對象的ArrayList)。本來期望第二個列表是ArrayList<String>
(字符串的ArrayList)。
當編譯類時,Groovy是否會丟失類型信息,並在編譯的類執行時推斷它?
實施例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()}"
輸出1
Untyped list List: class java.util.ArrayList
Typed list List<String>: class java.util.ArrayList // Would have expected ArrayList<String>
問題2
我本來期望的線typedList << new Integer(1)
在下面的例子中失敗,異常因爲我是試圖將一個int
放入一個字符串列表中。任何人都可以解釋爲什麼我可以添加一個int
到String
-?
輸出顯示它仍爲Integer
,即它不是即時轉換爲String
「1」。
實施例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() }
輸出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
http://stackoverflow.com/questions/15755261/groovy-map-and-java-map-on-generics –
@tim_yates:那麼根據鏈路的回答你發佈是「[...]這意味着類型參數在編譯時不被檢查,並且在運行時不可用。」這意味着我不能阻止任何人將'int'放入'List'中,這意味着我所能確定的是'List '包含'object'類型的對象。正確? –
Lernkurve
是的。除非你使用'@ CompileStatic' –