-1

Possible Duplicate:
Java generics and array initialization
How does one instantiate an array of maps in Java?

I know I can do :

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.

Community
  • 1
  • 1
fastcodejava
  • 39,895
  • 28
  • 133
  • 186
  • 1
    Just wondering, why don't you use a `List` instead of an old fashioned array? This question has by the way been asked a lot of times before. There might be some in the *Related* secton on the right column. – BalusC Sep 08 '11 at 04:58

1 Answers1

5

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>();
}

This is a consequence of erasure. The array is an array of HashMaps. 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.

Swaranga Sarma
  • 13,055
  • 19
  • 60
  • 93
sblundy
  • 60,628
  • 22
  • 121
  • 123