Java Long類型

public class Main {
    public static void main(String[] args) {
        Long l = null;
        System.out.println(l == 0L);
    }
}

沒想到居然報了空指針,我仔細(xì)的研究了一下包裝器。

public class Main {
    public static void main(String[] args) {
        Long l = null;
        Long l2 = 0L;
        long l3 = 0L;
        Long l4 = l3;
        System.out.println(l == 0L);
        System.out.println(l2 == 0L);
        System.out.println(l3 == 0L);
    }
}

jd-gui 瞧瞧.class文件

public class Main
{
  public static void main(String[] args)
  {
    Long l = null;
    Long l2 = Long.valueOf(0L);
    long l3 = 0L;
    Long l4 = Long.valueOf(l3);
    System.out.println(l.longValue() == 0L);
    System.out.println(l2.longValue() == 0L);
    System.out.println(l3 == 0L);
  }
}

編譯器做了一些操作

    public static Long valueOf(long l) {
        final int offset = 128;
        if (l >= -128 && l <= 127) { // will cache
            return LongCache.cache[(int)l + offset];
        }
        return new Long(l);
    }
    private static class LongCache {
        private LongCache(){}

        static final Long cache[] = new Long[-(-128) + 127 + 1];

        static {
            for(int i = 0; i < cache.length; i++)
                cache[i] = new Long(i - 128);
        }
    }
    private final long value;
    public long longValue() {
        return value;
    }

得到以下結(jié)論:

  1. Long類 內(nèi)部有LongCache靜態(tài)內(nèi)部類 有一個Long類型數(shù)組緩存-128~127。
  2. Long l1 = 0L 編譯器將其 Long l1 = Long.valueof(0L),如果不在cache范圍內(nèi),則new Long(0L);
  3. 0L 是 long 而不是Long
  4. 如果Long 為null,使用會出異常,因為longValue()方法。
  5. 以前只知道自動裝箱,自動拆箱,實際并沒有看過源碼,也沒有反編譯看過class,有一種恍然大悟的感覺。
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容