简体   繁体   中英

Adding to a hashmap inside of a hashmap

Here is what I have:

HashMap<String,HashMap<Integer,Integer>> data =
            new HashMap<String,HashMap<Integer,Integer>>();

But I am having trouble adding values to this, because the inner hashmap doesn't have a name (note: it isn't supposed to). I'm actually trying to add an array list to the first Integer in HashMap So I am trying something like:

data.put(var, data.get(array.get(x), y));

Which it very much doesn't like and I'm totally clueless as to how to do it.

Note that

HashMap<String,HashMap<Integer,Integer>> data =
            new HashMap<String,HashMap<Integer,Integer>>();

only creates the "outer" HashMap instance. After this statement you have an empty HashMap that takes Strings as keys and HashMap<Integer, Integer> as value.

You can add an instance of HashMap<Integer, Integer> to data with this:

data.put("myKey", new HashMap<Integer, Integer>());

After that you can add Integer values to the second HashMap:

data.get("myKey").put(123, 456); // use 123 as key and 456 as value

Get the values back:

data.get("myKey").get(123); // returns 456

You have to get the inner hash map first:

HashMap<Integer,Integer> innerData = data.get(var);

Then you can put your value into it:

innerData.put(x, y);
HashMap<String,HashMap<Integer,Integer>> data =
            new HashMap<String,HashMap<Integer,Integer>>();
((Map)data.get( "keyname" )).get(1);

and subsequently:

   ((Map)data.get( "keyname" )).get( 1 ).put(2);

Just do it like this:

data.put( var, new HashMap(intKey, intVal));

where intKey and intVal are Integer type Key and Integer type value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM