Integerの==

2570 ワード

package lan; 

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

i 1,i 2の値が-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);
	}
    }

 
上の2つのコードからInteger i=x(xは-128~127の数)がわかり、同じオブジェクトの参照が返され、この範囲を超えてのみIntegerオブジェクトが再作成されます.そのため、前の現象も説明した.