1

How can I put a hashmap inside an array?

HashMap<String, Object>[] config= null;
        config[0] = new HashMap<String, Object>(); 
        config[0].put("Name", "Jon");
        config[0].put("valueA", 0);
        config[1] = new HashMap<String, Object>(); 
        config[1].put("valueA", 2323);
ephramd
  • 481
  • 2
  • 15
  • 40

5 Answers5

4
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 HashMaps as part of the array constructor.

Woot4Moo
  • 22,887
  • 13
  • 86
  • 143
1

You can find some explanation here What's the reason I can't create generic array types in Java?

I propose to use next construction:

ArrayList<HashMap<String, Object>> config= new ArrayList<HashMap<String,Object>>();
HashMap<String, Object> map;
map = new HashMap<String, Object>();        
map.put("Name", "Jon");
map.put("valueA", 0);       
config.add(map); 
map = new HashMap<String, Object>();        
map.put("valueA", 2323);                        
config.add(map); 
Community
  • 1
  • 1
  • Thanks! It's works! And for read: `config.get(0).get("Name"); //Jon` edit/add: `config.get(0).put("Name", "Snow"));` – ephramd May 29 '13 at 07:00
0

Whilst you can declare an array of generics, you cannot instantiate them using the normal syntax.

Map<String,Object>[] config = new HashMap<String,Object>[10]; would give the compile error: Cannot create a generic array of HashMap

You can however use Array.newInstance see answers to this SO question

Community
  • 1
  • 1
FunkTheMonk
  • 10,631
  • 1
  • 27
  • 37
0

use ArrayList instead of a simple array.

            ArrayList<HashMap<String, Object>> arrayOfMap=new ArrayList<HashMap<String,Object>>();
anddevmanu
  • 1,409
  • 14
  • 19
0
Map<String,Object>[] config = new HashMap[10];

just leave the generic parameters away.

kutschkem
  • 6,194
  • 3
  • 16
  • 43