gpt4 book ai didi

Java:通过键从 Hashmap 获取对象

转载 作者:行者123 更新时间:2023-11-30 04:13:31 24 4
gpt4 key购买 nike

我尝试刷新我的 Java 技能。但现在我陷入了 HashMap 。我没有拿回正确的对象。这是我的示例代码:

public class Sample {

private static Map<String, Map<String, String>> peaks = new HashMap<String, Map<String, String>>();
private final String name;

public Sample(String name) {
this.name = name;
this.peaks = new HashMap<String, Map<String, String>>();
}

public static Map<String, Map<String, String>> getPeaks() {
return peaks;}

public static void addPeak(String peakName, String value) {
Map<String, String> peak = new HashMap<String, String>();
peak.put("value", value);
peaks.put(peakName, peak);
}
}

public class Main {
static Map<Integer, Sample> sample = new HashMap<Integer, Sample>();

public static void main(String[] args) {
Sample sam = new Sample("Test1");
sample.put(1, sam);
sample.get(1).addPeak("A", "1");

sam = new Sample("Test2");
sample.put(2, sam);
sample.get(2).addPeak("B", "123");

System.out.println(sample.get(1).getPeaks().toString());
System.out.println(sample.get(2).getPeaks().toString());
System.out.println(sample.get(4).getPeaks().toString());
}
}

每次输出都是:{B={value=123}}

我不知道哪个部分是错误的。我错过了什么吗?

最佳答案

此 map 是静态的:

private static Map<String, Map<String, String>> peaks = new HashMap<String, Map<String, String>>();

因此,每次调用 Sample.getPeaks() 都指向同一个 Map。

//getPeaks() returns the same map in both cases.
// In other words : sample.get(1).getPeaks() == sample.get(2).getPeaks()
System.out.println(sample.get(1).getPeaks().toString());
System.out.println(sample.get(2).getPeaks().toString());

// This is equivalent to
Map<String, Map<String, String>> myStaticMap = Sample.getPeaks();
System.out.println(myStaticMap.toString());
System.out.println(myStaticMap.toString());

关于Java:通过键从 Hashmap 获取对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19004559/

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