“Cannot create generic array of ..” – how to create an Array of Map?

Because of how generics in Java work, you cannot directly create an array of a generic type (such as Map<String, Object>[]). Instead, you create an array of the raw type (Map[]) and cast it to Map<String, Object>[]. This will cause an unavoidable (but suppressible) compiler warning.

This should work for what you need:

Map<String, Object>[] myArray = (Map<String, Object>[]) new Map[10];

You may want to annotate the method this occurs in with @SuppressWarnings("unchecked"), to prevent the warning from being shown.

Leave a Comment