自学内容网 自学内容网

Java包装类型的缓存

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

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

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

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

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()方法。 

Integer i = 10 //等价于 Integer i = Integer.valueOf(10)
int n = i //等价于 int n = i.intValue();


原文地址:https://blog.csdn.net/qq_73181349/article/details/144753887

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!