"Cannot create generic array of .." - how to create an Array of Map<String, Object>?
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.
I have had some difficulty with this, but I have figured out a few things that I will share as simply as possible.
My experience with generics is limited to collections, so I use them in the class definitions, such as:
public class CircularArray<E> {
which contains the data member:
private E[] data;
But you can't make and array of type generic, so it has the method:
@SuppressWarnings("unchecked")private E[] newArray(int size){ return (E[]) new Object[size]; //Create an array of Objects then cast it as E[]}
In the constructor:
data = newArray(INITIAL_CAPACITY); //Done for reusability
This works for generic generics, but I needed a list that could be sorted: a list of Comparables.
public class SortedCircularArray<E extends Comparable<E>> { //any E that implements Comparable or extends a Comparable class
which contains the data member:
private E[] data;
But our new class throws java.lang.ClassCastException:
@SuppressWarnings("unchecked")private E[] newArray(int size){ //Old: return (E[]) new Object[size]; //Create an array of Objects then cast it as E[] return (E[]) new Comparable[size]; //A comparable is an object, but the converse may not be}
In the constructor everything is the same:
data = newArray(INITIAL_CAPACITY); //Done for reusability
I hope this helps and I hope our more experienced users will correct me if I've made mistakes.