[Solved] Java – Unable to access a HashMap within a HashMap


I’m not sure that I really understand your description of what you are doing, but this stands out:

    this.containers.put(this.currentHashMapKey, tempHashMap);
    // ...
    tempHashMap.clear();

When you call clear(), you remove all entries from tempHashMap. Since this is the map object that you added as a value in the containers map, you are clearing it there as well.

One possible solution is to create a new tempHashMap on every iteration … and don’t call clear() after adding it to containers.


Explanation:

I thought it created a copy of the HashMap when you added it.

You appear to think that

    this.containers.put(this.currentHashMapKey, tempHashMap);

will create a copy of tempHashMap.

This is NOT so.

In fact, what you are doing is storing the reference to your “temporary hash map” as the entry value in the container map. Indeed, if you then reuse the temporary map, you will end up will many references to that one map object in your containers map.

A Map::put(key, value) operation does not copy / clone / whatever the key object or the value object. It just stores the references in the map entry. If you then mutate those objects:

  • mutating the value changes what is visible via the map
  • mutating the key breaks the mapping (!).

Will it not overwrite the previous HashMap whenever I create a new one though?

No it won’t. It creates a new one. Consider this:

    Map<String, String> tempHashMap = new HashMap<>();
    tempHashMap.put("key", "value");
    tempHashMap = new HashMap<>();

The third statement creates a new HashMap object and assigns the reference to the tempHashMap variable. That replaces the original reference value in the variable, but it does not affect the first HashMap object. If you still had a reference to the original object, you could still lookup “key” and get the corresponding “value”.

This is basic Java assihnment semantics. Assignment of objects (either by using =, or by passing a parameter) ONLY assigns references. It does NOT overwrite the actual object state.

This is different to C and C++ where assignment of objects (or structs) and assignment of pointers to objects / structs are fundamentally different operations.

4

solved Java – Unable to access a HashMap within a HashMap