• 包装类型的缓存机制


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

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

    Integer 缓存源码:

    1. public static Integer valueOf(int i) {
    2. if (i >= IntegerCache.low && i <= IntegerCache.high)
    3. return IntegerCache.cache[i + (-IntegerCache.low)];
    4. return new Integer(i);
    5. }
    6. private static class IntegerCache {
    7. static final int low = -128;
    8. static final int high;
    9. static {
    10. // high value may be configured by property
    11. int h = 127;
    12. }
    13. }

    Character 缓存源码:

    1. public static Character valueOf(char c) {
    2. if (c <= 127) { // must cache
    3. return CharacterCache.cache[(int)c];
    4. }
    5. return new Character(c);
    6. }
    7. private static class CharacterCache {
    8. private CharacterCache(){}
    9. static final Character cache[] = new Character[127 + 1];
    10. static {
    11. for (int i = 0; i < cache.length; i++)
    12. cache[i] = new Character((char)i);
    13. }
    14. }

    Boolean 缓存源码:

    1. public static Boolean valueOf(boolean b) {
    2. return (b ? TRUE : FALSE);
    3. }

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

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

    1. Integer i1 = 33;
    2. Integer i2 = 33;
    3. System.out.println(i1 == i2);// 输出 true
    4. Float i11 = 333f;
    5. Float i22 = 333f;
    6. System.out.println(i11 == i22);// 输出 false
    7. Double i3 = 1.2;
    8. Double i4 = 1.2;
    9. System.out.println(i3 == i4);// 输出 false

            下面我们来看一个问题:下面的代码的输出结果是 true 还是 false 呢?

    1. Integer i1 = 40;
    2. Integer i2 = new Integer(40);
    3. System.out.println(i1==i2);// 输出false

        Integer i1=40 这一行代码会发生装箱,也就是说这行代码等价于 Integer i1=Integer.valueOf(40) 。因此,i1 直接使用的是缓存中的对象。而Integer i2 = new Integer(40) 会直接创建新的对象。因此,答案是 false 。你答对了吗?

            记住:所有整型包装类对象之间值的比较,全部使用 equals 方法比较

    更多消息资讯,请访问昂焱数据。昂焱数据

  • 相关阅读:
    信号量机制
    【英雄哥六月集训】第 23天: 字典树
    使用 KerasCV YOLOv8 进行物体检测--附完整实现源码
    js判断数组包含某个值
    Linux操作系统之文件系统详解
    2022年最新《谷粒学院开发教程》:6 - 整合SpringCloud
    Python算法——树的重建
    【附源码】计算机毕业设计SSM商品测试应用管理系统
    YOLOv5涨点必备!改进损失函数EIoU,SIoU,AlphaIoU,FocalEIoU,Wise-IoU
    今年十八,喜欢ctf-web
  • 原文地址:https://blog.csdn.net/tszc95/article/details/134542982