-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.

1
  • 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. Commented Sep 8, 2011 at 4:58

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.