How to do an array of hashmaps? How to do an array of hashmaps? arrays arrays

How to do an array of hashmaps?


What gives? It works. Just ignore it:

@SuppressWarnings("unchecked")

No, you cannot parameterize it. I'd however rather use a List<Map<K, V>> instead.

List<Map<String, String>> listOfMaps = new ArrayList<Map<String, String>>();

To learn more about collections and maps, have a look at this tutorial.


You can use something like this:

import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;public class testHashes {public static void main(String args[]){    Map<String,String> myMap1 = new HashMap<String, String>();    List<Map<String , String>> myMap  = new ArrayList<Map<String,String>>();    myMap1.put("URL", "Val0");    myMap1.put("CRC", "Vla1");    myMap1.put("SIZE", "Val2");    myMap1.put("PROGRESS", "Val3");    myMap.add(0,myMap1);    myMap.add(1,myMap1);    for (Map<String, String> map : myMap) {        System.out.println(map.get("URL"));        System.out.println(map.get("CRC"));        System.out.println(map.get("SIZE"));        System.out.println(map.get("PROGRESS"));    }    //System.out.println(myMap);}}


The Java Language Specification, section 15.10, states:

An array creation expression creates an object that is a new array whose elements are of the type specified by the PrimitiveType or ClassOrInterfaceType. It is a compile-time error if the ClassOrInterfaceType does not denote a reifiable type (ยง4.7).

and

The rules above imply that the element type in an array creation expression cannot be a parameterized type, other than an unbounded wildcard.

The closest you can do is use an unchecked cast, either from the raw type, as you have done, or from an unbounded wildcard:

 HashMap<String, String>[] responseArray = (Map<String, String>[]) new HashMap<?,?>[games.size()];

Your version is clearly better :-)