1

It's 5am and I'm a bit asleep, so that may be it (also I'm relatively new with Java). But I don't see why this code generates Null Exception with this code. The map should be initialized by then, shouldn't it?

private static final Map<String, Integer> CONDS_MAP = 
    Collections.unmodifiableMap
    (
        new HashMap<String, Integer>()
            {{ 
                put("null", 0);
                put("false", 0);
                put("true", 1);
                put("numElems.lt", 2);
                put("NELT", 2);
                put("numElems.gt", 3);
                put("NEGT", 3);
            }}
    );

private int getCodeInt(Object code)
{
    if (code.getClass() == String.class)
    {
        return CONDS_MAP.get((String)code); // Null Exception here
    }
    else
    // (... etc etc)
}

Thanks! and sorry it it is too trivial...

4
  • 1
    Unrelated, but try to avoid the double brace HashMap initializer, and code.getClass() == String.class should be code instanceof String (easier to read, faster to type, avoids possible NPE). Commented Sep 23, 2011 at 3:42
  • @Thilo - What's wrong with an instance initializer? Commented Sep 23, 2011 at 3:44
  • @Ted: It creates an (unnecessary) subclass of HashMap. Commented Sep 23, 2011 at 3:46
  • @Thilo: Thanks for you recommendation! Commented Sep 23, 2011 at 3:51

2 Answers 2

6

It is most likely caused by trying to unbox the null returned from a non-existing key.

return CONDS_MAP.get((String)code);

is the same as

return CONDS_MAP.get(code).intValue();

That last intValue will fail if the Map returns null.

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

4 Comments

I could swear that I put the dot in that json... but nah, code was "numElemsgt". Thanks. Sleeping may help. And also I will check for null values.
Different strings should return the same int. (I'll update the example)
Sure, but you could still say put(NUM_ELEMS_GT, 3); instead of put("numElems.gt", 3);
I don't see it working for me: I am using for reading data from a JSON file, and converting some Strings from the file to integer codes that later on are going to be switch'd.
0

Yes it has been initialized by then, the nullpointerexception is probably caused by a null key.

2 Comments

Does a null key cause a NullPointerException ?
@Thilo Yes according to the docs - download.oracle.com/javase/6/docs/api/java/util/…

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.