Integer自動梱包の問題

2360 ワード

1、テストクラス:
public class IntegerTest {

	public static void main(String[] args) {
		
		Integer m = 200;
		Integer n = 200;
		System.out.println(m == n);
		
		Integer i = 100;
		Integer j = 100;
		System.out.println(i == j);
	}
}

 :
--------------------------------------------------------------------------------
false
true
--------------------------------------------------------------------------------

2、このクラスを逆コンパイルする:
public class Integertest
{
  public static void main(String[] paramArrayOfString)
  {
    Integer localInteger1 = Integer.valueOf(200);
    Integer localInteger2 = Integer.valueOf(200);
    System.out.println(localInteger1 == localInteger2);

    Integer localInteger3 = Integer.valueOf(100);
    Integer localInteger4 = Integer.valueOf(100);
    System.out.println(localInteger3 == localInteger4);
  }
}

3、Integerを確認する.valueOf()ソース:
public static Integer valueOf(int i) {
		// -128  IntegerCache.high , cache    new 
		if (i >= -128 && i <= IntegerCache.high)
			return IntegerCache.cache[i + 128];
		else
			return new Integer(i);
}



private static class IntegerCache {
		// 
		static final int high;
		// 
		static final Integer cache[];

		static {
			//   
			final int low = -128;
			//   
			int h = 127;
			//integerCacheHighPropValue jvm    -XX:AutoBoxCacheMax=    
			if (integerCacheHighPropValue != null) {
				int i = Long.decode(integerCacheHighPropValue).intValue();
				i = Math.max(i, 127);
				h = Math.min(i, Integer.MAX_VALUE - -low);
			}
			high = h;
			// (high-low)+1 cache
			cache = new Integer[(high - low) + 1];
			int j = low;
			for (int k = 0; k < cache.length; k++)
				cache[k] = new Integer(j++);
		}

		private IntegerCache() {
		}
}

4、まとめ:
1)、Integer Integer.valueOf(int i) 
2)、 AutoBoxCacheMax , i <=127 >=-128 ,Integer.valueOf() Integer , Integer 。
3)、  false、true