对Integer类中的私有IntegerCache缓存类的一点记录

对Integer类中的私有IntegerCache缓存类的一点记录

  // Integer类有内部缓存,存贮着-128 到 127。
  // 所以,每个使用这些数字的变量都指向同一个缓存数据
  // 因此可以直接使用 == 来比较是否相等
  Integer a = 88;
  Integer b = 88;
  System.out.println(a == b); // true

  // 下面这个不在Integer缓存类里的数字,在每次赋值的时候都会新建一个对象存放
  // 所以,它们不能使用 == 来判断是否相等,而只能使用equals方法来比较
  Integer d = 800;
  Integer c = 800;
  System.out.println(d == c); // false
  System.out.println(d.equals(c)); // true

猜你喜欢

转载自www.cnblogs.com/molisiye/p/9162483.html