java包装类的自动装箱及缓存

  首先看下面一段代码

 1 public static void main(String[] args) {
 2         Integer a=1;
 3         Integer b=2;
 4         Integer c=3;
 5         Integer d=3;
 6         Integer e=321;
 7         Integer f=321;
 8         Long g=3L;
 9         System.out.println(c==d);
10         System.out.println(e==f);
11         System.out.println((a+b)==c);
12         System.out.println(c.equals(a+b));
13         System.out.println(g==(a+b));
14         System.out.println(g.equals(a+b));
15     }

  这段代码最终运行的结果是true,false,true,true,true,false.产生原因如下

  第9行:c,d两个类被赋值一个int型值,该int型数字会自动装箱,变成包装类Integer,由于Integer类是存在缓存的,缓存大小为-128~187,3被包括在缓存中,装箱会自动将缓存中的对象返回,所以c,d是指向同一个对象的.

  第10行:321不在缓存中,装箱会返回一个新的对象,所以e,f是不同的对象

  第11行:a+b返回一个值为3的Integer,在缓存中,是同一个对象

  第12行:a+b值类型为Integer,值为3,相等

  第13行:a+b的结果会被强转为Long,在缓存中,是同一个对象

  第14行:a+b是int型,g是long类型,所以不相等

  包装类缓存大小如下:

  • Boolean:(全部缓存)
  • Byte:(全部缓存)
  • Character(<= 127缓存)
  • Short(-128 — 127缓存)
  • Long(-128 — 127缓存)
  • Integer(-128 — 127缓存)
  • Float(没有缓存)
  • Doulbe(没有缓存)

ps:

 包装类在遇到算数运算符时会自动拆箱 

原文地址:https://www.cnblogs.com/ouhaitao/p/8590680.html