[英]Initialize map of map in java
If I have a Map of Map in Java and I initialized the outer map, then what will be the value of the inner map (null or new Map()) ? 如果我具有Java中的Map映射,并且初始化了外部映射,那么内部映射的值是什么(空值或new Map())?
For example, I have: 例如,我有:
Map<User, Map<Component, Float>> summaryByEmp = new TreeMap<>();
Now, what will be the value of the inner map? 现在,内部地图的价值是什么? Do I need to initialize too?
我也需要初始化吗?
There is something wrong with your understanding of Map
here. 您对此处的
Map
的理解有误。 Doing 在做
Map<User, Map<Component, Float>> outerMap = new TreeMap<User, Map<Component, Float>>()
initializes a TreeMap
referenced by outerMap
. 初始化由
outerMap
引用的TreeMap
。 The type parameter only says that, the key to be put needs to be of type User
and the value to the key to be of type Map<Component, Float>
. type参数仅表示,要放置的密钥必须是
User
类型,并且密钥的值必须是Map<Component, Float>
。 Nothing more. 而已。
So when you insert a key-value pair of type mentioned, you insert it to the TreeMap
. 因此,当您插入提到的类型的键值对时,会将其插入到
TreeMap
。
Your map summaryByEmp will be empty utill you add some key value pair in your map. 您在地图中添加一些键值对后,地图summaryByEmp将为空。 So question
那么问题
what will be the value of inner map
内部地图的价值是什么
does not arises at very first place 不会出现在第一位
Map<User, Map<Component, Float>> summaryByEmp = new TreeMap<>();
If you want to add it 如果要添加
Map<Component, Float> innerMap = new TreeMap();
summaryByEmp.put(new User(),innerMap )
It will have no value, just like the type User
, Component
and Float
. 它将没有值,就像类型
User
, Component
和Float
。 You will need to add data to the map like: 您将需要向地图添加数据,例如:
Map<Component, Float> mapVal = new TreeMap<>();
/// Fill mapVal
User u = new User();
summaryByEmp.put(u, mapVal);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.