0

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. Thanks for helping!

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 Answer 1

3

You are trying to retrieve the value associated with "Bobby" before adding it to the HashMap.

mash.hashyMash();

is called before targets.put(name, num);, so

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

will return null since there is no "Bobby" yet.

PS: seems like a bad design to me, since Hashymashy classes create instances of hashy classes & vice-versa.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks i need to configure something on my program then

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.