Integer 缓存

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

内存中的 Integer 对象

  1. 缓存范围

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

  2. 使用 new 创建对象

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

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

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

sql 复制代码
   
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)。如果是,它会返回缓存中的对象,而不是创建新的对象。
sql 复制代码
`public static Integer valueOf(int i) {
    if (i >= Integer.MIN_VALUE && i <= 127) {
        return IntegerCache.cache[i + 128]; // 返回缓存中的对象
    }
    return new Integer(i); // 超出范围时,创建新对象
}`
相关推荐
野犬寒鸦2 小时前
从零起步学习Redis || 第十二章:Redis Cluster集群如何解决Redis单机模式的性能瓶颈及高可用分布式部署方案详解
java·数据库·redis·后端·缓存
悟能不能悟11 小时前
redis的红锁
数据库·redis·缓存
酷ku的森18 小时前
Redis的缓存更新策略
缓存
野犬寒鸦20 小时前
从零起步学习Redis || 第十一章:主从切换时的哨兵机制如何实现及项目实战
java·服务器·数据库·redis·后端·缓存
callJJ1 天前
缓存雪崩、击穿、穿透是什么与解决方案
缓存
如竟没有火炬1 天前
LRU缓存——双向链表+哈希表
数据结构·python·算法·leetcode·链表·缓存
阿湯哥1 天前
Redis数据库隔离业务缓存对查询性能的影响分析
数据库·redis·缓存
麦兜*1 天前
Redis 7.2 新特性实战:Client-Side Caching(客户端缓存)如何大幅降低延迟?
数据库·spring boot·redis·spring·spring cloud·缓存·tomcat
he___H1 天前
尚庭公寓中Redis的使用
数据库·redis·缓存·尚庭公寓
不良人天码星2 天前
redis-zset数据类型的常见指令(sorted set)
数据库·redis·缓存