JAVA拆箱与装箱及cache范围 博客分类: Java Integer.valueOf()装箱拆箱valueOf缓存范围Character [0~127]
程序员文章站
2024-03-11 15:26:19
...
1. 调用Integer.valueOf()时, 对[-128,127]进行了缓存!
public final class Integer extends Number implements Comparable<Integer> { private static class IntegerCache { private IntegerCache(){} static final Integer cache[] = new Integer[-(-128) + 127 + 1]; static { for(int i = 0; i < cache.length; i++) cache[i] = new Integer(i - 128); } } public static Integer valueOf(int i) { final int offset = 128; if (i >= -128 && i <= 127) { // must cache return IntegerCache.cache[i + offset]; } return new Integer(i); } }
2. 装箱与拆箱的本质:
装箱: 自动Integer.valueOf();
Integer jjj = 1;
编译后源码:
Integer jjj = Integer.valueOf(1);
拆箱: 自动对象.intValue();
int jjj = new Integer(2);
编译后源码:
int jjj = (new Integer(2)).intValue();
EG:
示例代码:
public class Test { public static void main(final String[] args) { Integer a = 100; Integer b = 100; System.out.println(a == b); main2(); main3(); } public static void main2() { Integer a = 156; Integer b = 156; System.out.println(a == b); } public static void main3() { int a = new Integer(156); int b = Integer.valueOf(156); System.out.println(a == b); } }
经过装箱拆箱本质代码为:
public class Test { public static void main(String[] args) { Integer a = Integer.valueOf(100); Integer b = Integer.valueOf(100); System.out.println(a == b); main2(); main3(); } public static void main2() { Integer a = Integer.valueOf(156); Integer b = Integer.valueOf(156); System.out.println(a == b); } public static void main3() { int a = new Integer(156).intValue(); int b = Integer.valueOf(156).intValue(); System.out.println(a == b); } }
运行结果:
true false true
3. yekui说, 查了一下源码,确实如此!
java使用该机制是为了达到最小化数据输入和输出的目的,这是一种优化措施,提高效率.
valueOf缓存范围
其他的包装器:
Boolean: (全部缓存)
Byte: (全部缓存)
Character [0, 127] 缓存
Short [-128, 127] 缓存
Long [-128, 127] 缓存
Float (没有缓存)
Doulbe (没有缓存)