Integer类相关问题

Integer类是int类型对应的包装类,从 Java 5 开始引入了自动装箱/拆箱机制,使得二者可以相互转换。

下面记录j几个问题

问题一:

Integer num1 = new Integer(40);
Integer num2 = 40;	//自动装箱,相当于Integer num2 = new Integer(40);
int num3 = 40;

System.out.println(num1 == num2);	//false
//在进行比较的时候,num1自动拆箱为inty类型的40,即相当于int num1 = 40;
System.out.println(num1 == num3);  //true 
System.out.println(num2 == num3);  //true

第一个输出为false,是因为num1与num2比较的是两个对象的地址,故为false。

问题二:

Integer num1 = 127, num2 = 127, num3 = 128, num4 = 128;
		
System.out.println(num1 == num2);	//true
System.out.println(num3 == num4);	//false

首先需要注意的是 num1、 num2、 num3、 num4 四个变量都是 Integer 对象引用,所以==运算比较的不是值而是引用。

当我们给一个 Integer 对象赋一个 int 值的时候,会调用 Integer 类的静态方法 valueOf,valueOf的源码如下:

/**
  * Returns an {@code Integer} instance representing the specified
   * {@code int} value.  If a new {@code Integer} instance is not
   * required, this method should generally be used in preference to
   * the constructor {@link #Integer(int)}, as this method is likely
   * to yield significantly better space and time performance by
   * caching frequently requested values.
   *
   * This method will always cache values in the range -128 to 127,
   * inclusive, and may cache other values outside of this range.
   *
   * @param  i an {@code int} value.
   * @return an {@code Integer} instance representing {@code i}.
   * @since  1.5
   */
  public static Integer valueOf(int i) {
      if (i >= IntegerCache.low && i <= IntegerCache.high)
          return IntegerCache.cache[i + (-IntegerCache.low)];
      return new Integer(i);
  }

简单的说,如果整型字面量的值在-128 到 127 之间,那么不会 new 新的 Integer 对象,而是直接引用常量池中的 Integer 对象,所以上面的问题中num1 == num2 的结果是 true,而 num3 == num4 的结果是 false。

猜你喜欢

转载自blog.csdn.net/weixin_40374341/article/details/86302101