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?
A stab in the dark: is there an entry in your map for the particular character assigned to
c
? If there isn't, Java may be trying to unbox a null value...If there is no entity with required
Character
in map, thenmap.get(key)
returnsnull
and insideif
statement it leads toNullPointerException
throwing.Your code is very messy.
Here is a working version :
If
c
is not contained inmyMap
, it will returnnull
, which can't be unboxed as aboolean
.Try :
Change
to
Changing this
For this
Will make use of the map's defined method to check if a certain key is registered on the map. I'm leaving the
for
as it is, since you seem to want to check for a group of keys.myMap.get(c)
returns the value associated with that key, ornull
if the key is not registered.As a side note, remember that if you use this method with custom objects you'll have to redefine the
hashcode
andequals
methods.Suggestion: I'm just suggesting this out of a remote idea I have, if it's not a correct interpretation of your code just ignore it. If your map only contains a boolean value to determine if certain value "is contained" or not, I strongly suggest you use a
HashSet
instead because a map is not doing any sense in that context.