I have code similar to the following :-
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 doo(String input)
{
StringBuilder output = new StringBuilder();
for ( char c : input.toCharArray() )
{
if ( myMap.get(c) )
output.append(c);
}
}
...
...
}
I get a null pointer exception at the line if ( myMap.get(c) )
-- What am I doing wrong?
If
myMap
doesn't contain a key that matchesc
, thenmyMap.get(c)
will return null. In that case, when the JVM unboxes what it expects to be ajava.lang.Boolean
object into aboolean
primitive to execute the condition, it founds a null object and therefore throws ajava.lang.NullPointerException
.The following block is equivalent to what you have in your example and should make it easier to understand why you would have a
NullPointerException
:I would re-write your original condition as:
I hope this helps.