gpt4 book ai didi

java - 实现两个 HashMap

转载 作者:行者123 更新时间:2023-11-30 05:06:24 25 4
gpt4 key购买 nike

我正在尝试实现两个 HashMap 的组合。下面是我的代码,但我无法生成我真正想要的东西。我的代码的结果是:

{{userId1=clientID1}=timestamp1}
{{userId1=clientID1, userId2=clientID2}=timestamp2, {userId1=clientID1, userId2=clientID2}=timestamp1}

实际上我需要:

{{userId1=clientID1}=timestamp1},{userId2=clientID2}=timestamp2},{userId3=clientID3}=timestamp3}..}

也就是说,一对一的映射。我们真的可以实现这个要求吗?如果没有,任何人都可以建议一种这种类型的映射的方法。我将非常感激......

public static void main (String args[]) 
{
HashMap map = new HashMap<String, String>();
HashMap<HashMap,String> multi = new HashMap();
map.put("userId1", "clientID1");
multi.put(map, "timestamp1");

System.out.println(multi); //gives me correct requirement

map.put("userId2", "clientID2");
multi.put(map, "timestamp2");

System.out.println(multi); //since the table is filled again a combination of values results(each time it keeps on increasing) which is not really required as per my requirement .Hope my problem is clear.please do help me ..
}

最佳答案

为什么不能简单地使用两个单独的映射,一个是 userId -> clientId,另一个是 userId -> timestamp?最初使用 Map 作为 Map 的键的原因是什么?

请记住,Map 在 Java 中是可变的,并且使用可变对象作为 Map 的键通常是一种非常糟糕的做法。

关于java - 实现两个 HashMap,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4968476/

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