简体   繁体   中英

put(key, value) in Multi-level hashMap in java

The program is as below:

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

HashMap<String, String> person = new HashMap<String, String>();
        person.put("Name", json.getString("Name"));
        person.put("Contact", json.getString("Contact"));
        person.put("Email", json.getString("Email"));
        person.put("Rent Start", json.getString("Rent Start"));
        person.put("Rent End", json.getString("Rent End"));

String period = json.getString("Rent Start").substring(0, 7) + " To " + json.getString("Rent End").substring(0, 7);

data.get(roomType).put(period, person);

Assume "data" is not empty in each level. Problem occurs in the following step.

data.get(roomType).put(period, person);

When I do so, all values in the hashmap that in the second level become the person hashmap.

For example, in "roomtype1", there are 2 period, "2015-07 To 2016-07" and "2015-07 To 2017-07".

When I run this code:

data.get(roomtype1).put("2015-07 To 2016-07", person);

the hashmap got by

data.get(roomtype1).get("2015-07 To 2017-07");

also becomes person .

May I know why?

(ps The original hashmap has 5 levels. I reduced it for this post because it will be easier to be understood)

Java objects are reference type.

data.get(key1) will get the hashmap object in the second level. with that object you are adding one more object into it.

When I do so, all values in the hashmap that in the second level become the addition hashmap.

What does data.get(roomType) ? Is it doing something like:

public V get(K key) {
  V actual = super.get(key);
  if (null == actual) {
    actual = getANewV();
    super.put(key, actual);
  }
  return actual;
}

And are you sure that the getANewV() always returns a new instance and not the same (which would explains all values in the hashmap that in the second level become the addition hashmap ).

And your need already exists in the matter of Multimap (see Guava). You should probably see if that work for you. Beside, I'd personally use object rather than multiple layer of maps.

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