gpt4 book ai didi

Java:嵌套 Hashmap 的问题

转载 作者:太空宇宙 更新时间:2023-11-04 07:39:48 26 4
gpt4 key购买 nike

我有一个嵌套的LinkedHashMap看起来像这样:

LinkedHashMap<String,LinkedHashMap<String,LinkedList<Long>>> map = new...

问题是每个外部 map 只添加 1 个内部 map ,而我期待 2 个。我认为问题在于我如何构建我的 map ,并用第二个内部 map 覆盖第一个内部 map 。 (简单总结一下我的程序,我将每只手映射到每个手指。映射结构需要是 Finger={Right_Hand=[],Left_Hand=[] ,反之亦然。)

构造函数:

Set<String> handNames = new HashSet<String>(Arrays.asList("Left","Right");
Set<String> fingerNames = new HashSet<String>(Arrays.asList("Pinky","Ring","Middle","Index","Thumb");
LinkedHashMap<String, LinkedHashMap<String,LinkedList<Long>>> fingerHandMap = new LinkedHashMap<String, LinkedHashMap<String,LinkedList<Long>>>();

createNestedMap() {
for (String finger : fingerNames)
for (String hand : handNames) {
LinkedHashMap<String, LinkedList<Long>> handMap = new LinkedHashMap<String, LinkedList<Long>>();
handMap.put(hand, new LinkedList<Long>());
fingerHandMap.put(finger, handMap);
}
}

但是,当我打印 map 时,它看起来像这样:
{Ring={Left=[]}, Pinky={Left=[]}, Thumb={Left=[]}, Middle={Left=[]}, Index={Left=[]}}

我将如何创建独特的 LinkedLists ,让 map 看起来像:
{Ring={Right=[], Left=[]}, Pinky={Right=[], Left=[]}, Thumb={Right=[], Left=[]}, Middle={Right=[], Left=[]}, Index={Right=[], Left=[]}}

谢谢!

最佳答案

我将在伪代码中写下您当前正在执行的操作,因此希望您可以看到自己做错了什么:

create a new finger hand map
for each finger:
for each hand:
create a new hand map
put an entry mapping the hand to an empty list in the hand map
put an entry mapping the finger to the hand map in the finger hand map

请记住,当您 put映射中的键值条目,它会用相同的键替换任何现有条目。

如果您需要进一步说明,请告诉我。

关于Java:嵌套 Hashmap 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16245935/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com