简体   繁体   English

Generics上的Groovy地图和Java地图

[英]Groovy map and Java map on Generics

I am new to Groovy, and I have a question regarding to the use of map: 我是Groovy的新手,我对使用map有疑问:

I know I can do: 我知道我能做到:

def map = [key:"value"]

But what does it mean if I do this: 但是如果我这样做意味着什么:

Map<String, String> map = ["1":1, "2":"2"]

This code compiles, but the map is not really a String->String map: 此代码编译,但映射实际上不是String-> String映射:

map.each({println it.key + ":" + it.value + "[" + it.value.class + "]"})

It prints: 它打印:

1:1[class java.lang.Integer] 1:1 [类java.lang.Integer]

2:2[class java.lang.String] 2:2 [类java.lang.String]

Can anyone helps me to understand how come a map explicitly typed with String->String can be assigned to a map object that contains String->Integer? 任何人都可以帮助我理解如何使用String-> String显式键入地图可以将字符串分配给包含String-> Integer的地图对象? Thank you! 谢谢!

=== Update === ===更新===

Thanks for the link provided by @GrailsGuy, if I am using @TypeChecked for the above code wrapped in a method, it will throw an error: 感谢@GrailsGuy提供的链接,如果我将@TypeChecked用于包含在方法中的上述代码,则会抛出错误:

[Static type checking] - Incompatible generic argument types. Cannot assign java.util.Map <java.lang.String, java.io.Serializable> to: java.util.Map <String, String>

The explanation makes perfect sense now. 这个解释现在很有意义。

This forum post talks about Groovy ignoring generics, specifically: 这个论坛帖子谈论Groovy忽略泛型,特别是:

Groovy is a dynamically typed language, but you can statically declare the types of variables. Groovy是一种动态类型语言,但您可以静态声明变量类型。 Generics on the JVM are erased at compile time and only the raw type is available to the VM (this is true both for groovy and Java). JVM上的泛型在编译时被擦除,只有原始类型可供VM使用(对于groovy和Java都是如此)。 In Java, there is compile time checking to ensure that you don't stuff an int into a list of strings. 在Java中,有编译时检查以确保您不将int填充到字符串列表中。 But, Groovy does not check types at compile time. 但是,Groovy不会在编译时检查类型。

So, this means that the type parameter is not checked at compile time and not available at runtime. 因此,这意味着在编译时不检查type参数,并且在运行时不可用。

Eric, 埃里克,

I suspect this is caused by type erasure explained here and here . 我怀疑这是由此处此处解释的类型擦除引起的。 Since groovy is compiled into byte code, at the byte code level the parameterized types are removed. 由于groovy被编译为字节代码,因此在字节代码级别删除参数化类型。 Thus, 从而,

Map<String, String> objMap is compiled into Map objMap . Map<String, String> objMap is compiled into Map objMap

Thus it is composed by keys and object values.This is the reason why groovy code compiles and runs without errors. 因此它由键和对象值组成。这就是为什么groovy代码编译和运行没有错误的原因。 Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM