でInteger class
、ありますprivate static class IntegerCache
。
このクラスの用途は何ですか?
使用中の利点は何Integer
ですか?
IntegerCache は、オートボクシングを最適化するために -128 から +127 の間の値をキャッシュします。
または127
を使用して上限を設定できます-XX:AutoBoxCacheMax=NEWVALUE
-Djava.lang.Integer.IntegerCache.high=NEWVALUE
その実装を見てください:
private static class IntegerCache {
static final int high;
static final Integer cache[];
static {
final int low = -128;
int h = 127;
if (integerCacheHighPropValue != null) {
int i = Long.decode(integerCacheHighPropValue).intValue();
i = Math.max(i, 127);
h = Math.min(i, Integer.MAX_VALUE - -low);
}
high = h;
cache = new Integer[(high - low) + 1];
int j = low;
for(int k = 0; k < cache.length; k++)
cache[k] = new Integer(j++);
}
private IntegerCache() {}
}
Integer
256 個の値が再度使用できるようにキャッシュされ、最初のオブジェクトを作成するときに読み込まれます。
したがって、==
演算子を使用してInteger
[-127,128] の範囲で 2 つの s が等しいかどうかをチェックすると、2 つの s を比較したかのようになりますint
。Integer
しかし、 を使用してこの範囲外の2 つの を比較すると、同じ値であっても==
が得られます。false