Integer解读

在这里插入图片描述
在这里插入图片描述
涉及自动装箱和拆箱的过程。
源码:
在这里插入图片描述
1、使用自动装箱(Integer i = 1)方式创建Integer对象时,会使用valueOf进行Integer对象的初始化,此时,会调用IntegerCache.high,这是需要对IntegerCache这个静态内部类进行初始化。
2、IntegerCache类中有一个cache数组,在加载IntegerCache的时候,会将-128到127的Integer对象都创建了,并存到cache数组中,然后在判断当前初始化的Integer对象的值是否在-128到127之间,如果是,就直接从cache缓存中取,如果不存在,则new一个新的Integer对象。
3、之后再使用自动装箱的方式创建Integer对象时,值在-128到127之间时会直接从cache缓存中取。

使用自动装箱的方式创建的Integer对象,两者进行比较时,只要其值相等就是ture。而不在-128到127之间的,比较时会新new一个对象,而导致比较结果为false。
这个是Integer的缓存策略,用来节省内存和提高性能。整型对象在内部实现中通过使用相同的对象引用实现了缓存和重用。
注意:Integer的最低值是固定的,只能是-128,而最高值是可以通过jvm参数设置的。在执行java程序的时候加上-XX:AutoBoxCacheMax=参数即可。
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

Long的缓存机制(LongCache)与Integer的类似,还有Character(CharacterCache),Byte(ByteCache)的缓存机制也是类似。不过只有Integer的最大值可以通过jvm参数设置,其他的都固定的。其中,Byte,Short,Long 的范围: -128 到 127;Character, 范围是 0 到 127。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以对代码进行一些优化,主要是减少重复的数据库查询和代码块重复。 优化后的代码如下: ```java Long userId = SecurityUtils.getUserId(); boolean flag = permissionService.hasRole("brand"); // admin if (SecurityUtils.isAdmin(userId)) { Integer capacity = gsApparatusExampleMapper.selectCapacityNum(); Integer userCapacity = gsApparatusExampleMapper.selectUserCapacityNum(); return capacity - userCapacity; } if (flag) { // 品牌 Long brandId = UserUtils.getBrandId(userId); List<GsShop> gsShops = gsShopMapper.selectList(Wrappers.<GsShop>lambdaQuery() .eq(GsShop::getBrandId, brandId)); List<Long> shopIds = gsShops.stream().map(GsShop::getId).collect(Collectors.toList()); Integer result = 0; Integer userResult = 0; for (Long shopId : shopIds) { Integer capacity = gsApparatusExampleMapper.selectCapacity(shopId); Integer userCapacity = gsApparatusExampleMapper.selectUserCapacity(shopId); result += (capacity != null ? capacity : 0); userResult += (userCapacity != null ? userCapacity : 0); } return result - userResult; } // 店铺 Long shopId = UserUtils.getShopId(userId); Integer capacity = gsApparatusExampleMapper.selectCapacity(shopId); Integer userCapacity = gsApparatusExampleMapper.selectUserCapacity(shopId); capacity = (capacity != null ? capacity : 0); userCapacity = (userCapacity != null ? userCapacity : 0); return capacity - userCapacity; ``` 优化说明: 1. 将管理员权限判断提前,避免不必要的数据库查询。 2. 使用 `selectCapacityNum` 和 `selectUserCapacityNum` 方法一次性查询容量和使用容量的总和。 3. 统一处理容量和使用容量的 null 值情况,避免重复代码。 4. 将品牌用户和店铺用户的逻辑合并,避免代码块重复。 5. 使用两个变量 `result` 和 `userResult` 分别累加容量和使用容量,在最后返回它们的差值。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值