Java:通过密钥从Hashmap获取对象

时间:2013-09-25 12:11:16

标签: java hashmap

我尝试刷新我的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}}

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

3 个答案:

答案 0 :(得分:1)

这张地图是静态的:

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

因此,对Sample.getPeaks()的每次调用都指向同一个地图。

//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());   

答案 1 :(得分:1)

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

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

答案 2 :(得分: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()