1

我尝试更新我的 Java 技能。但现在我卡在了一个哈希图上。我没有得到正确的对象。这是我的示例代码:

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}}

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

4

3 回答 3

1

这张地图是静态的:

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());   
于 2013-09-25T12:21:27.500 回答
1

方法getPeaksaddPeaks地图peaks都是静态的!这意味着它们只存在一次(每个类),而不是每个 Sample 实例存在一次。

因此,每次创建新Sample实例时,都会覆盖peaks构造函数中的静态字段!删除static关键字!

于 2013-09-25T12:21:48.343 回答
0

也许您正在尝试学习如何使用嵌套地图,但是对于此实现,您不能简单地创建一个Map<String, String>? 我问的原因是因为addPeak您已经peak.put("value", value)使用硬编码字符串“value”调用了 ,这可能是不必要的。这是一些可能满足您感兴趣的代码:

public class WhyMapOfMap {

    // Simpler map
    private Map<String, String> peaks;
    private String name;

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

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

    public void addPeak(String peakName, String value) {
        peaks.put(peakName, value);
    }
}

然后就可以正常访问地图了sample.get(key).getPeaks()

于 2013-09-25T17:35:27.283 回答