public class Main {
public static void main(String[] args) {
Long l = null;
System.out.println(l == 0L);
}
}
沒想到居然報(bào)了空指針,我仔細(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é)論:
- Long類 內(nèi)部有LongCache靜態(tài)內(nèi)部類 有一個(gè)Long類型數(shù)組緩存-128~127适室。
- Long l1 = 0L 編譯器將其 Long l1 = Long.valueof(0L),如果不在cache范圍內(nèi)伴澄,則new Long(0L);
- 0L 是 long 而不是Long
- 如果Long 為null,使用會出異常擒权,因?yàn)閘ongValue()方法疫稿。
- 以前只知道自動裝箱鸵隧,自動拆箱,實(shí)際并沒有看過源碼荒典,也沒有反編譯看過class酪劫,有一種恍然大悟的感覺。