package com.test;
public class Test {
   public static void main(String []args) {
     Integer a = 100;//此处若使用new,则==值必为false
     Integer b = 100;
     System.out.println(a==b);//true

     Integer c = 150;

     Integer d = 150;

     System.out.println(c==d);//false

   }
}
打印结果很显然。如果换成 127 >= var >= -128 之外的整数就打false了。
这是什么原因呢?
1、java在编译的时候 Integer a = 100; 被翻译成-> Integer a = Integer.valueOf(100);

 

 

public static Integer valueOf(int i) { 
final int offset = 128; 
if (i >= -128 && i <= 127) { // must cache 
return IntegerCache.cache[i + offset]; //符合值范围时候,进入也创建好的静态IntergerCache,i+offset的值表示去取cache数组中那个下标的值

return new Integer(i); //当不符合-128 127值范围时候。记住用的:new,开辟新的内存空间,不属于IntergerCache管理区

相关文章:

  • 2022-01-24
  • 2022-12-23
  • 2021-10-24
  • 2022-02-07
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-07-19
猜你喜欢
  • 2022-12-23
  • 2021-07-30
  • 2021-10-16
  • 2021-06-17
  • 2021-05-24
  • 2021-09-20
  • 2021-08-05
相关资源
相似解决方案