简体   繁体   English

Java HashMaps为什么会返回null?

[英]Java HashMaps why does this return null?

I setup a test jar app to run for my other program I have been working on this for hours and i cant find a reason for why it returns null. 我设置了一个测试jar应用程序来为我的其他程序运行,我已经为此工作了几个小时,但我找不到它返回null的原因。 Thanks for helping! 感谢您的帮助!

hashy.java 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 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+"!");
}
}

You are trying to retrieve the value associated with "Bobby" before adding it to the HashMap . 您试图将与“ Bobby”相关的值添加到HashMap

mash.hashyMash();

is called before targets.put(name, num); targets.put(name, num);之前被调用targets.put(name, num); , so ,所以

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

will return null since there is no "Bobby" yet . 将返回null ,因为没有"Bobby"

PS : seems like a bad design to me, since Hashymashy classes create instances of hashy classes & vice-versa. PS:似乎是一个不好的设计给我,因为Hashymashy类创建的实例hashy类和反之亦然。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM