• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
小小慧
博客园    首页    新随笔    联系   管理    订阅  订阅
Java Integer的底层优化

看一个程序(腾讯题)

public class showMain {
    public static void main(String[] args){
        //Double i1=127.00,i2=127.00,i3=128.00,i4=128.00;    //输出 false true false true
        Integer i1=127,i2=127,i3=128,i4=128;                //输出 true true false true
        //Integer i1=127,i2=127,i3=120,i4=120;               //输出 true true true true
        System.out.println(i1==i2);
        System.out.println(i1.equals(i2));
        System.out.println(i3==i4);
        System.out.println(i3.equals(i4));
    }
}

因为Integer 有底层优化,源代码如下

public static Integer valueOf(int i) {
    final int offset = 128;
    if (i >= -128 && i <= 127) { // must cache 
        return IntegerCache.cache[i + offset];
    }
        return new Integer(i);
    }

就是说    小于等于127会从cache里取,大于会new

posted on 2016-09-02 10:04  小小慧  阅读(512)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3