J
J
Jsman2016-02-19 16:53:29
Java
Jsman, 2016-02-19 16:53:29

How to add HashMap value to HashMap?

There are two HashMap's
HashMap> AccommodationMapOur = new HashMap();
HashMap AccommodationMapOurTwo = new HashMap();
AccommodationMapOur.put("1", AccommodationMapOurTwo);
AccommodationMapOur.put("2", AccommodationMapOurTwo);
We get : {2={}, 1={}} ;
How to get such a value {2={3=3}, 1={4=4}} ;
I don’t understand how for each key of the first hashmap to make a different key value for the second hashmap =(

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis Zagaevsky, 2016-02-19
@SeniorDmitry

First, what is it? Have you been banned from using generics?
Let's see what we have here. We have a Map in which the key is a string, the value is another Map. OK.

HashMap<String, String> accommodationMapOurTwo = new HashMap<>(); //пустая Map
accommodationMapOur.put("1", accommodationMapOurTwo); //Ok, запихали в первую мапу вторую.
accommodationMapOur.put("2", accommodationMapOurTwo); //Ok, сделали это ещё раз, не забываем, что в джаве всё - ссылка.

That is, you need to add a new Map each time, right?
for (int i = 0; i < 100500; ++i) {
    HashMap<String, String> newMap = new HashMap<>();
    newMap.put(String.valueOf(i + 10), String.valueOf(i + 20));
    accommodationMapOur.put(String.valueOf(i), newMap);
}

For example, yes.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question