How does one instantiate an array of maps in Java?

how to get array values from hashmap in java
array of maps in c++
cannot create a generic array of hashmap
hashmap 2d array java
hashmap java
convert map to 2d array java
int array to hashmap java
java array

I can declare an array of maps using generics to specify the map type:

private Map<String, Integer>[] myMaps;

However, I can't figure out how to instantiate it properly:

myMaps = new HashMap<String, Integer>[count]; // gives "generic array creation" error
myMaps = new HashMap[count]; // gives an "unchecked or unsafe operation" warning
myMaps = (Map<String, Integer>[])new HashMap[count]; // also gives warning

How can I instantiate this array of maps without getting a compiler error or warning?

Update:

Thank you all for your replies. I ended up going with the List suggestion.

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 an Object array variable, which is legal because arrays are covariant. Line 4 stores the List<Integer> into the sole element of the Object array, which succeeds because generics are implemented by erasure: the runtime type of a List<Integer> instance is simply List, and the runtime type of a List<String>[] instance is List[], so this assignment doesn’t generate an ArrayStoreException. Now we’re in trouble. We’ve stored a List<Integer> instance into an array that is declared to hold only List<String> instances. In line 5, we retrieve the sole element from the sole list in this array. The compiler automatically casts the retrieved element to String, but it’s an Integer, 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.

ArrayMap (Oracle Fusion Middleware Java API Reference for Oracle , How do you create an array of maps in Java? Notice here the data type of key and value of the Map is same. In order to make it more generic let's take the array of Objects and perform the same operation: Map<String, Integer> map = Stream.of(new Object[][] { { "data1", 1 }, { "data2", 2 }, }).collect(Collectors.toMap(data -> (String) data[0], data -> (Integer) data[1]));

Not strictly an answer to your question, but have you considered using a List instead?

List<Map<String,Integer>> maps = new ArrayList<Map<String,Integer>>();
...
maps.add(new HashMap<String,Integer>());

seems to work just fine.

See Java theory and practice: Generics gotchas for a detailed explanation of why mixing arrays with generics is discouraged.

Update:

As mentioned by Drew in the comments, it might be even better to use the Collection interface instead of List. This might come in handy if you ever need to change to a Set, or one of the other subinterfaces of Collection. Example code:

Collection<Map<String,Integer>> maps = new HashSet<Map<String,Integer>>();
...
maps.add(new HashMap<String,Integer>());

From this starting point, you'd only need to change HashSet to ArrayList, PriorityQueue, or any other class that implements Collection.

Convert HashMap To ArrayList In Java, How do you create an array of objects in Java? Array in Java is an object that holds multiple values in a single variable. Array in Java is based on the index. Each item in an array called an element, There are two types of Array in Java:

In general it is not a good idea to mix generics and arrays in Java, better use an ArrayList.

If you must use an array, the best way to handle this is to put the array creation (your example 2 or 3) in a separate method and annotate it with @SuppressWarnings("unchecked").

how to create an array of maps, It is error: Cannot create generic array of Map<String, Object> However, you can create a list of a generic type. Any ideas how can I do it? The java.util.Arrays class has several methods named fill() which accept different types of arguments and fill the whole array with the same value: long array[] = new long[5]; Arrays.fill(array, 30); The method also has several alternatives which set a range of an array to a particular value: int array[] = new int[5]; Arrays.fill(array, 0, 3, -50);

Short answer appears to be that you really just can't.

See the following for a blog about it. http://www.bloggingaboutjava.org/2006/01/java-generics-quirks/

One of the comments to the blog states that:

Actually, the engineers made the creation of such an Array illegal. So the creation of an array from generic Class fails. The Collection.toArray method followed by a Cast to the Array works at compile time.

This solves not the problem, that the ArrayStoreCheck can’t be done during Runtime, but you can create an Array of generics in this way.

As suggested by Bill the Lizard, you probably are better off using a

List<Map<String,Integer>>

Convert Map to an Array in Java, In this post, we will see how to convert Map to an Array in Java. 1. Map to Array of Map.Entry<K,V>. We can easily get an object array of Map.Entry<K,V> using  The reason the first one works is because the compiler can check how many elements you are going to assign to the array, and then allocate the appropriate amount of memory. EDIT: I realize now that you are just trying to update array1 with new data

You can create generic array of map

  1. Create list of map.

     List<Map<String, ?>> myData = new ArrayList<Map<String, ?>>();
    
  2. Initialize array.

     Map<String,?>[]myDataArray=new HashMap[myData .size()];
    
  3. Populate data in array from list.

     myDataArray=myData.toArray(myDataArry);
    

Array of HashMaps (Beginning Java forum at Coderanch), Win a copy of Modern Programming Made Easy: Using Java, Scala, I m trying to create an array of HashMaps in the following way on NetBeans 6.8 1. HashMap[] map = new HashMap[ 10 ]; Use a collection class instead of an array, for example an ArrayList - because that can be resized dynamically. One-Dimensional Arrays : The general form of a one-dimensional array declaration is. type var-name[]; OR type[] var-name; Instantiating an Array in Java. var-name = new type [size]; For Example

Creating and storing arrays in a map : Map « Collections « Java , Creating and storing arrays in a map : Map « Collections « Java Tutorial. array[​0] = 0; array[1] = 1; array[2] = 2; map.put("array", array); Iterator<String> iter = map​. Creating a Type-Specific Map: creates a map whose keys are Integer objects and values are String objects. Create an array containing the keys in a map. How to Instantiate an Object in Java. Webucator provides instructor-led training to students throughout the US and Canada. We have trained over 90,000 students from over 16,000 organizations on technologies such as Microsoft ASP.NET, Microsoft Office, Azure, Windows, Java, Adobe, Python, SQL, JavaScript, Angular and much more.

Arrays of objects | Think Java, One possibility is a String containing things like "Spade" for suits and "Queen" for ranks. We mean to define a mapping between a sequence of numbers and the Or we can create the array and initialize the elements at the same time, as we  Instantiating an Object of ArrayList. Listing 1 illustrates an object called rowList, which is an array of arrays. As you can see, the data type is Object[]. This data type allows for a flexible approach. Listing 1 Instantiating an Object of ArrayList ArrayList<Object[]> rowList = new ArrayList<Object[]>();

Initializing arrays in Java, Arrays are a helpful data type for managing elements in contiguous memory location. There are many other ways to initialize an array in Java. What I mean by "array-like" is that a Map defines a collection of objects whose 

Comments
  • The example is IMO not convincing. You can already break type safety far easier with plain arrays - look at ArrayStoreException.
  • That's part of the point. Arrays are arguably broken because they're covariant -- you can assign a Subclass array to something that wants a Superclass array. At least you get the ArrayStoreException the instant you try to insert something that shouldn't be in the array. With generics, you wouldn't even get the exception. Because of erasure, a List<T> performs no runtime checking that the thing you're inserting is actually of type T. The checking is all done at compile time, so it's all the more important that the types be statically sound.
  • You beat me by seconds. I might suggest you use Collection instead, that way you can switch to a Set implementation if you need to as well.
  • @Drew: Great idea! I'll add it to my answer as an alternative.
  • The link you posted says that the leagl way to do what the OP wants is myMaps = new Map<?,?>[count]. But it also says that this is a dangerous thing to do, and that mixing arrays and generic containers is a bad thing in general.
  • somebody should tell this to Springframework team, who expect you provide them an array of generic Maps for JDBC batch operations: NamedParameterJdbcTemplate.batchUpdate(String sql, Map<String, ?>[] batchValues) docs.spring.io/spring-framework/docs/current/javadoc-api/org/…
  • @SuppressWarnings is the only way to not get a warning, but why separate method? I feel annotating the assignment is a better choice.
  • The warning is saying that something is being done wrong. Just suppressing it is a really bad idea.
  • @Tom Hawtin If it were always wrong it would be an error and not a warning. So with due care it is sometimes (rarely) ok to suppress a warning, if there is no better way to achieve the same goal.
  • That's not right: "Type mismatch: cannot convert from Map<String,Integer> to Map<String,Integer>[]".
  • Strange, you're correct - guess I never did that in practice.