Alex Rivera | Logout

Java HashMap get method null pointer exception

Asked 2012-12-03T16:17:17.627
31

My code is similar to the following:

public class A {
        private HashMap<Character, Boolean> myMap;

        public A() {
            myMap = new HashMap<Character, Boolean>();
            String mychars = "asdfzxcvqwer";
            for (char c : mychars.toCharArray())
                myMap.put(c, true);
        }

        public void doo(String input) {
            StringBuilder output = new StringBuilder();
            for (char c : input.toCharArray()) {
                if (myMap.get(c))
                    output.append(c);
            }
        }
        //...
        //...
    }

Why am I getting a null pointer exception (NPE) at the line if (myMap.get(c))?

Edit
Report

1 Answer

4

If there is no entity with required Character in map, then map.get(key) returns null and inside if statement it leads to NullPointerException throwing.

answered 2012-12-03T16:19:35.033

Your Answer