Java HashMaps为什么返回null?

时间:2015-12-27 09:52:08

标签: java hashmap

我设置了一个测试jar应用程序来运行我的其他程序我已经工作了几个小时,我找不到为什么它返回null的原因。谢谢你的帮助!

hashy.java

import java.util.HashMap;

public class hashy {

private static HashMap<String, Integer> targets = new HashMap<String, Integer>();

public static void main(String[] args) {
    Hashymashy mash = new Hashymashy();
    mash.hashyMash();
    String name = "Bobby";
    int num = 10;

    targets.put(name, num);

    if (targets.containsKey(name) == true) {
        System.out.println("It contains a key!");
    } else {
        System.out.println("It does not contain a key!");
    }
    if (targets.containsValue(num) == true) {
        System.out.println("It contains a value");
    } else {
        System.out.println("It does not contain a value!");
    }
}
public HashMap<String,Integer> getTargets(){
    return targets;
}
}

Hashymashy.java

 public class Hashymashy {

public void hashyMash(){
    hashy h = new hashy();
    String name = "Bobby";
    Integer fnum = h.getTargets().get(name);

    System.out.println("Number is "+fnum+"!");
}
}

1 个答案:

答案 0 :(得分:3)

您尝试检索与“Bobby”相关联的值,然后再将其添加到HashMap

mash.hashyMash();
targets.put(name, num);之前调用

,所以

Integer fnum = h.getTargets().get("Bobby");

将返回null,因为没有"Bobby"

PS :对我来说似乎是一个糟糕的设计,因为Hashymashy类创建hashy类的实例&amp;反之亦然。