Cannot create generic array of .. - how to create an Array of MapString, 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.
What's the reason I can't create generic array types in Java?
It's because Java's arrays (unlike generics) contain, at runtime, information about its component type. So you must know the component type when you create the array. Since you don't know what T
is at runtime, you can't create the array.
Generic array creation error
You can't have arrays of generic classes. Java simply doesn't support it.
You should consider using a collection instead of an array. For instance,
public static ArrayList<List<MyObject>> a = new ArrayList<List<MyObject>();
Another "workaround" is to create an auxilliary class like this
class MyObjectArrayList extends ArrayList<MyObject> { }
and then create an array of MyObjectArrayList
.
Here is a good article on why this is not allowed in the language. The article gives the following example of what could happen if it was allowed:
List<String>[] lsa = new List<String>[10]; // illegal
Object[] oa = lsa; // OK because List<String> is a subtype of Object
List<Integer> li = new ArrayList<Integer>();
li.add(new Integer(3));
oa[0] = li;
String s = lsa[0].get(0);
How does one instantiate an array of maps in Java?
You can't safely create a generic array. Effective Java 2nd Edition goes into the details in the chapter on Generics. Start at the last paragraph of page 119:
Why is it illegal to create a generic
array? Because it isn’t typesafe. If
it were legal, casts generated by the
compiler in an otherwise correct
program could fail at runtime with a
ClassCastException
. This would violate
the fundamental guarantee provided by
the generic type system.To make this more concrete, consider
the following code fragment:// Why generic array creation is illegal - won't compile!
List<String>[] stringLists = new List<String>[1]; // (1)
List<Integer> intList = Arrays.asList(42); // (2)
Object[] objects = stringLists; // (3)
objects[0] = intList; // (4)
String s = stringLists[0].get(0); // (5)
Let’s pretend that line 1, which
creates a generic array, is legal.
Line 2 creates and initializes a
List<Integer>
containing a single
element. Line 3 stores the
List<String>
array into anObject
array variable, which is legal because
arrays are covariant. Line 4 stores
theList<Integer>
into the sole
element of theObject
array, which
succeeds because generics are
implemented by erasure: the runtime
type of aList<Integer>
instance is
simplyList
, and the runtime type of a
List<String>[]
instance isList[]
, so
this assignment doesn’t generate an
ArrayStoreException
. Now we’re in
trouble. We’ve stored aList<Integer>
instance into an array that is
declared to hold onlyList<String>
instances. In line 5, we retrieve the
sole element from the sole list in
this array. The compiler automatically
casts the retrieved element toString
,
but it’s anInteger
, so we get a
ClassCastException
at runtime. In
order to prevent this from happening,
line 1 (which creates a generic array)
generates a compile-time error.
Because arrays and generics don't combine well (as well as other reasons), it's generally better to use Collection
objects (in particular List
objects) rather than arrays.
Cannot create an array of LinkedLists in Java...?
You can't use generic array creation. It's a flaw/ feature of java generics.
The ways without warnings are:
Using List of Lists instead of Array of Lists:
List< List<IntegerNode>> nodeLists = new LinkedList< List< IntegerNode >>();
Declaring the special class for Array of Lists:
class IntegerNodeList {
private final List< IntegerNode > nodes;
}
Java: How to create an array of MapString,Object objects
You really cant. You have to do it like this:
@SuppressWarnings("unchecked")
HashMap<String, Object>[] map = new HashMap[20000];
How to create a generic array in Java?
I have to ask a question in return: is your GenSet
"checked" or "unchecked"?
What does that mean?
Checked: strong typing.
GenSet
knows explicitly what type of objects it contains (i.e. its constructor was explicitly called with aClass<E>
argument, and methods will throw an exception when they are passed arguments that are not of typeE
. SeeCollections.checkedCollection
.-> in that case, you should write:
public class GenSet<E> {
private E[] a;
public GenSet(Class<E> c, int s) {
// Use Array native method to create array
// of a type only known at run time
@SuppressWarnings("unchecked")
final E[] a = (E[]) Array.newInstance(c, s);
this.a = a;
}
E get(int i) {
return a[i];
}
}Unchecked: weak typing. No type checking is actually done on any of the objects passed as argument.
-> in that case, you should write
public class GenSet<E> {
private Object[] a;
public GenSet(int s) {
a = new Object[s];
}
E get(int i) {
@SuppressWarnings("unchecked")
final E e = (E) a[i];
return e;
}
}Note that the component type of the array should be the erasure of the type parameter:
public class GenSet<E extends Foo> { // E has an upper bound of Foo
private Foo[] a; // E erases to Foo, so use Foo[]
public GenSet(int s) {
a = new Foo[s];
}
...
}
All of this results from a known, and deliberate, weakness of generics in Java: it was implemented using erasure, so "generic" classes don't know what type argument they were created with at run time, and therefore can not provide type-safety unless some explicit mechanism (type-checking) is implemented.
How can I put a hashmap inside an array? conf[0] = new HashMapString, Object();
List<Map<String, String>[]> listOfMaps = new ArrayList<Map<String, String>[]>();
should be sufficient. You don't instantiate it with the ()
since it is an array, you need to provide it a size or a series of HashMap
s as part of the array constructor.
Related Topics
What's the Correct Way to Send a File from Rest Web Service to Client
How to Match "Any Character" in Regular Expression
No Exception While Type Casting with a Null in Java
Differences Between Java 8 Date Time API (Java.Time) and Joda-Time
Does Java Have a Int.Tryparse That Doesn't Throw an Exception for Bad Data
Difference Between One-To-Many, Many-To-One and Many-To-Many
How to Convert/Parse from String to Char in Java
Inter Thread Communication in Java
The Split() Method in Java Does Not Work on a Dot (.)
Arrays.Aslist(Int[]) Not Working
How I Save and Retrieve an Image on My Server in a Java Webapp
Multiple Packages in Context:Component-Scan, Spring Config
Correct Way of Throwing Exceptions with Reactor
How Does Java Store Strings and How Does Substring Work Internally
Convert Arraylist into 2D Array Containing Varying Lengths of Arrays
Java.Sql.Sqlexception: Incorrect String Value: '\Xf0\X9F\X91\Xbd\Xf0\X9F...'