NullPointerException and unboxing [duplicate]

2019-06-20 17:15发布

This question already has an answer here:

I have two almost equal pieces of code (see below) that do NOT work the same, but in my opinion should work the same.

The first one is the buggy version that throws NullPointerException and the second one just works. NPE happens when assigning getNewIndex result to maxIdx. The question is why?

Incorrect version throwing NPE:

Integer maxIdx = fieldName.equals(Fields.KEYS) ? 1 :
            getNewIndex(field.getGroup(), Fields.KEYS, Fields.PARAMS);

And the correct working version:

Integer maxIdx = fieldName.equals(Fields.KEYS) ? 1 : null;
if (maxIdx == null) {
    maxIdx = getNewIndex(field.getGroup(), Fields.KEYS, Fields.PARAMS);
}

And if anyone is wondering. I'm using Oracle Java 1.8.0_45

1条回答
ら.Afraid
2楼-- · 2019-06-20 17:17

The auto unboxing happens because the 1 sets the result of the ternary operation to be an int.

The Integer returned by getNewIndex is null, which causes the NPE when unboxing.

You can use new Integer(1) instead to avoid the unboxing.

查看更多
登录 后发表回答