看一个程序(腾讯题)

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

相关文章:

  • 2021-07-04
  • 2021-10-05
  • 2021-11-23
  • 2021-12-09
  • 2021-07-13
  • 2021-09-28
猜你喜欢
  • 2022-12-23
  • 2021-08-26
  • 2022-12-23
  • 2022-12-23
  • 2021-12-23
  • 2021-07-21
  • 2021-08-15
相关资源
相似解决方案