Java包装类型的缓存

果超出对应范围仍然会去创建新的对象,缓存的范围区间的大小只是在性能和资源之间的权衡。Java 基本数据类型的包装类型的大部分都用到了缓存机制来提升性能。这 4 种包装类默认创建了数值。的相应类型的缓存数据,两种浮点数类型的包装类。并没有实现缓存机制。

Java 基本数据类型的包装类型的大部分都用到了缓存机制来提升性能。

Byte,Short,Integer,Long这 4 种包装类默认创建了数值 [-128,127] 的相应类型的缓存数据,Character 创建了数值在 [0,127] 范围的缓存数据,Boolean 直接返回 True or False

果超出对应范围仍然会去创建新的对象,缓存的范围区间的大小只是在性能和资源之间的权衡。

两种浮点数类型的包装类 Float,Double 并没有实现缓存机制。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
public static void main( String[] args )
    {
        Integer i1 = 128;
        Integer i2 = 128;
        System.out.println(i1 == i2);// 输出 false

        Integer i3 = 33;
        Integer i4 = 33;
        System.out.println(i3 == i4);// 输出 true

        Float i11 = 333f;
        Float i22 = 333f;
        System.out.println(i11 == i22);// 输出 false

        Double i5 = 1.2;
        Double i6 = 1.2;
        System.out.println(i6 == i5);// 输出 false

        Integer i7 = 40;
        Integer i8 = new Integer(40);
        System.out.println(i7==i8);//输出false,因为i7直接用的缓存,i8则是创建的对象,存在堆
    }

装箱其实就是调用了 包装类的valueOf()方法,拆箱其实就是调用了 xxxValue()方法。

1
2
Integer i = 10 //等价于 Integer i = Integer.valueOf(10)
int n = i //等价于 int n = i.intValue();
comments powered by Disqus
使用 Hugo 构建
主题 StackJimmy 设计