Joshua Joshua - 1 month ago 5
Java Question

Can't get HashMap to work

So I'm using the following code, but for some reason it won't let me enter any values into the contacts HashMap, it just says "contacts.put(name, number)=null", but I can't see where I'm going wrong. Any help? Thanks!

public class MapTester {

private HashMap<String, String> contacts;

public MapTester() {
HashMap<String, String> contacts = new HashMap<>();
}

public void enterNumber(String name, String number) {
contacts.put(name, number);
}

public String lookupNumber(String name) {
return contacts.get(name);
}
}

Answer

Try the following. You need to initialise the HashMap before using it and make is accessible throughout your class.

public class MapTester {

    private HashMap<String, String> contacts;

    public MapTester() {
        contacts = new HashMap<>();
    }

    public void enterNumber(String name, String number) {
        contacts.put(name, number);
    }

    public String lookupNumber(String name) {
        return contacts.get(name);
    }

}
Comments