Integer之==

本文深入探讨了Java中Integer对象的缓存机制。当Integer值位于-128到127之间时,会复用已有的对象,这有助于节省内存并提高性能。文章还详细分析了Integer.valueOf方法的实现,并通过反汇编进一步验证了这一行为。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package lan; 

public class Test { 
        public static void main(String[] args) { 
       	 Integer i1 = 4; 
       	 Integer i2 = 4; 
       	 System.out.println(i1 == i2); 
        } 
} 

当i1、i2的值在-128~127之间时,输出true,否则为false。

java language specification-3.0 写道
If p is a value of type int, then boxing conversion converts p into a reference r of class and type Integer, such that r.intValue() == p
If the value p being boxed is true, false, a byte, a char in the range \u0000 to \u007f, or an int or short number between -128 and 127, then let r1 and r2 be the results of any two boxing conversions of p. It is always the case that r1 == r2.

在命令行通过JDK自带的反汇编工具javap对.class文件进行反汇编:javap -c Test

Compiled from "Test.java"
public class lan.Test extends java.lang.Object{
public lan.Test();
  Code:
   0:   aload_0
   1:   invokespecial   #8; //Method java/lang/Object."<init>":()V
   4:   return

public static void main(java.lang.String[]);
  Code:
   0:   iconst_4
   1:   invokestatic    #16; //Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
   4:   astore_1
   5:   iconst_4
   6:   invokestatic    #16; //Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
   9:   astore_2
   10:  getstatic       #22; //Field java/lang/System.out:Ljava/io/PrintStream;
   13:  aload_1
   14:  aload_2
   15:  if_acmpne       22
   18:  iconst_1
   19:  goto    23
   22:  iconst_0
   23:  invokevirtual   #28; //Method java/io/PrintStream.println:(Z)V
   26:  return

}

 可以看出Integer i = 4实际上就是 Integer i = Integer.valueOf(4);于是查看JDK源代码:

 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);
    }

 

 private static class IntegerCache {
	private IntegerCache(){}

	static final Integer cache[] = new Integer[-(-128) + 127 + 1];

	static {
	    for(int i = 0; i < cache.length; i++)
		cache[i] = new Integer(i - 128);
	}
    }

 

从上面两段代码可以看出Integer i = x(x为-128~127之间的数),返回的是同一个对象的引用,只有超出这个范围才会重新创建一个Intger对象。因此也就解释了前面的现象。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值