我如何检查空指针异常

Arm*_*ada 1 java hashmap nullpointerexception

这是代码

private static HashMap naturalNumbers = new HashMap();

static
{
    naturalNumbers.put("zero", new Integer( 0 ) );
    naturalNumbers.put("one", new Integer( 1 ) );
    naturalNumbers.put("two", new Integer( 2 ) );
    naturalNumbers.put("three", new Integer( 3 ) );
}

private static int findANumber( String partOfaNumber ) throws Exception
{
int multiplicand = 0;  
multiplicand += (Integer)naturalNumbers.get( partOfaNumber );
Run Code Online (Sandbox Code Playgroud)

如果"get"返回null,我该如何检查?

我试过了:

if ( (Integer)naturalNumbers == null )
    {
        throw new Exception( "Number not found" );
    }
 return multiplicand;
}
Run Code Online (Sandbox Code Playgroud)

但IDE甚至不接受它:无法从HashMap转换为Integer.

小智 5

这是一个略有不同的版本:

private static final HashMap<String, Integer> NUMS = new HashMap<String, Integer>();

static
{
    NUMS.put("zero", 0);
    NUMS.put("one", 1);
    NUMS.put("two", 2);
    NUMS.put("three", 3);
}

private static int findANumber(final String partOfaNumber) throws IllegalArgumentException
{
    int multiplicand = 0;  
    final Integer theNum = NUM.get(partOfaNumber);
    if (theNum != null) {
        multiplicand += theNum;
    } else {
        throw new IllegalArgumentException("Number not found (" + partOfNumber + ")");
    }

    return multiplicand;
}
Run Code Online (Sandbox Code Playgroud)