问题地图数组泛型 [英] Problem with map array with generics
问题描述
可能重复:结果
Java泛型和数组初始化结果
<一href=\"http://stackoverflow.com/questions/1493162/how-does-one-instantiate-an-array-of-maps-in-java\">How做一件实例在Java中的地图数组?
我知道我可以做的:
Map<String, Object> map = new HashMap<String, Object>();
所以我应该能够:
so I should be able to :
Map<String, Object>[] maps = new HashMap<String, Object>[10];
但是,这并不工作,使编译的问题。
but this does not work, gives compilation problem.
推荐答案
这是在Java泛型的怪癖。你必须声明数组像这样:
That's a quirk of generics in java. You have to declare the array like so:
HashMap<String, Object>[] maps = new HashMap[10];
后,你可以亲手创建的每个地图,例如:
later you can create each Map personally, example :
for(int i=0;i<10;i++)
{
maps[i] = new HashMap<String,Object>();
}
这是擦除的结果。该数组是的HashMap
组成的数组。泛型类型参数不保留。你会得到一个关于此警告,但它会编译并可以坐席preSS与 @燮pressWarning(未登记)
标注的警告
This is a consequence of erasure. The array is an array of HashMap
s. The generic type param is not retained. You'll get a warning about this, but it will compile and you can suppress the warning with the @SuppressWarning("unchecked")
annotation.
这篇关于问题地图数组泛型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!