当前位置: 首页 > article >正文

Integer 缓存

在 Java 中,如果你通过 new Integer(value) 显式创建一个 Integer 对象,以下几点需要注意:

内存中的 Integer 对象

  1. 缓存范围

    Java 自动缓存的 Integer 对象范围是从 -128127。这些对象在类加载时被创建并存储在内存中。

  2. 使用 new 创建对象

    当你使用 new Integer(value) 创建一个整数对象时,无论 value 的值是 -1270100 还是 128,都会创建一个新的 Integer 对象。即使这个值在缓存范围内,new 关键字也不会返回缓存中的对象。

`Integer a = new Integer(100);   // 创建新对象
Integer b = new Integer(100);   // 又创建一个新对象
System.out.println(a == b);      // 输出: false`
  1. 缓存对象的存在

    缓存的对象在内存中始终存在,直到 JVM 结束。你可以通过 Integer.valueOf(int value) 方法获取缓存对象。

   
Integer c = Integer.valueOf(100);   // 使用缓存
Integer d = Integer.valueOf(100);   // 同样使用缓存
System.out.println(c == d);          // 输出: true

import java.util.HashMap;
import java.util.Map;

public class IntegerCache {
private static final Map<Integer, Integer> cache = new HashMap<>();

static {
    for (int i = -128; i <= 127; i++) {
        cache.put(i, i);
    }
}
public static Integer valueOf(int value) {
    return cache.getOrDefault(value, new Integer(value));
}

public static void main(String[] args) {
    Integer a = IntegerCache.valueOf(100);
    Integer b = IntegerCache.valueOf(100);
    System.out.println(a == b);  // 输出: true

    Integer x = IntegerCache.valueOf(200);
    Integer y = IntegerCache.valueOf(200);
    System.out.println(x == y);  // 输出: false
}


}

总结

  • 使用 new Integer(value) 会创建新对象,而不会使用缓存的对象。
  • 缓存的 Integer 对象(-128 到 127)在内存中始终存在,但通过 new 创建的对象不会与这些缓存对象相同。
  • 若要利用缓存,使用 Integer.valueOf(int) 方法是最佳选择。
  • 返回缓存对象:当你调用 Integer.valueOf(int value) 时,该方法会检查传入的值是否在缓存范围内(-128 到 127)。如果是,它会返回缓存中的对象,而不是创建新的对象。
`public static Integer valueOf(int i) {
    if (i >= Integer.MIN_VALUE && i <= 127) {
        return IntegerCache.cache[i + 128]; // 返回缓存中的对象
    }
    return new Integer(i); // 超出范围时,创建新对象
}`

http://www.kler.cn/news/303678.html

相关文章:

  • Three.js 实战【4】—— 3D地图渲染
  • 【Linux 从基础到进阶】Docker 容器技术基础与应用
  • MySQL事务【后端 13】
  • triton之ttir学习
  • 在C++中,如何避免出现Bug?
  • 第二百三十一节 JPA教程 - JPA Transient示例、 JPA ID注释示例
  • 【ArcGIS Pro】扩展模块 Nuget 使用
  • 【TabBar嵌套Navigation案例-cell重用 Objective-C语言】
  • 【git】.gitignore文件:版本控制的守护者
  • CICD 持续集成与持续交付
  • 论文速读|形机器人的高速和抗冲击远程操作
  • 【LabVIEW学习篇 - 23】:简单状态机
  • 【Android安全】Ubuntu 16.04安装GDB和GEF
  • Shell脚本函数与数组(Linux篇)
  • sql severs 递归查询
  • seafaring靶场漏洞测试攻略
  • MATLAB移动目标检测与追踪系统
  • 数据结构—线性表和顺序表
  • 【系统分析师】计算机组成与体系架构
  • 基于ssm框架的学生社团管理系统APP---附源码75171
  • JavaScript的事件介绍
  • MySQL_SQLYog简介、下载及安装(超详细)
  • 【深度学习】PyTorch 的发展历程 截止 2.1.0
  • 茅台镇酱香型白酒你知道多少?
  • MongoDB日志级别
  • 如何在本地Windows运行hadoop
  • conda 安装tensorflow一些命令
  • 人工智能在鼻咽癌诊断和治疗中的应用进展、当前挑战和未来前景|文献精析·24-09-13
  • 苹果CMS海洋CMS那个更容易被百度收录?苹果CMS站群
  • 输电线路在线监测摄像头:规格(一)