hashmap如何在java中对嵌套映射中的多个条目使用单个键
我有一个问题,使用嵌套贴图可能不是理想的解决方案,但需要一些反馈
这是存在的泛型结构,其中水果、蔬菜、玩具是映射中的键,而另一个映射又与之关联,其中新鲜、不新鲜、腐烂是映射“b”的键
private Map<String, Commodity> Comm = new HashMap<String, Commodity>();
for (Map.Entry<String, Map<String, Object>> e : this.entrySet()) {
Comm.put(e.getKey(), getCommodity(e.getValue(), e.getKey()));
}
private Commodity getCommodity(Map<String, Object> m, String section) {
return new Commodity(m, section);
}
Fruit=> Fresh=>object
notFresh=>object
rotten=>object
Vegetable=> fresh=> object
notfresh=>object
rotten=>object
Toys=> fresh=>object
notfresh=>object
rotten=>object
但是,我需要介绍另一个关键点,称为“季节”,其中,如果提到商品的季节,则商品属于季节,否则如前所述保持不变
i.e
Fruit=> winter =>Fresh=>object
notFresh=>object
rotten=>object
Vegetable=> fresh=> object
notfresh=>object
rotten=>object
Toys=> summer => fresh=>object
notfresh=>object
rotten=>object
所以在这种情况下,水果和玩具有一个季节,在这种情况下,它需要在冬季寻找水果,在夏季寻找玩具。如何在java中实现这种复杂的映射结构
# 1 楼答案
你是对的,它“可能不是理想的解决方案”。地图是保存一个键和一个值的机制。一个简单的映射,如果你想的话。它们并不像你试图做的那样,用来构建复杂的数据结构。正如你自己看到的,它变得非常复杂和奇怪。所以不要这样做
改为自己上课。类是生成数据结构的Java方法。首先,绘制数据外观的草图:
shop
)如果我错了,请纠正我,但我就是这样理解你的问题的。如果我错了,你可以自己纠正细节
现在我们有5个要点,我们可以把它们分成5类我在做这件事时,没有让事情变得简单的能手和二传手:
现在,你可以用它来把你的商店放在一起:
注:
# 2 楼答案
正如托马斯所说,这不是理想的解决方案。然而,为了测试它,你可以这样做:
我想我正确地理解了结构。如果没有,请建议
这个输出
这张地图看起来像:
# 3 楼答案
也许你可以用一个物体来表达地图的关键点。java HashMap使用对象的
hashCode
进行快速比较——当键发生冲突时,它会回退到equals
(@seeHashMap
.getEntry(object key))