Why does the Java compiler sometimes allow the unboxing of null?

后端 未结 3 1221
梦谈多话
梦谈多话 2021-02-19 02:52

For example:

int anInt = null;

fails at compile time but

public static void main(String[] args) {
  for (int i = 0; i < 10;          


        
3条回答
  •  别那么骄傲
    2021-02-19 02:58

    Boxing partially hides the distinction between primitives and corresponding wrapper objects, but it doesn't remove it.

    There are two distinctions which are not changed by boxing:

    • objects can be null, while primitives cannot
    • objects have both state and identity, while primitives have only state (the value)

    Occasionally, these differences can cause problems when using boxing.

    Some points to remember :

    • be careful with nulls. Auto-unboxing a null object will cause a NullPointerException.
    • comparing items with == and equals must be done with care.

提交回复
热议问题