JavaのIntegerクラスがキャッシュする範囲
-128~127の範囲とは限らない

JavaのIntegerクラスにキャッシュがあることを知る
JetBrains公式アカウントで以下のクイズがポストされていた。
解答の中に以下のツイートを発見。
Not equal because they are greater than 127. 127 and below would use the integer cache and then they would be equal
— Simon Martinelli (@simas_ch) May 17, 2025
“Integer cache"なるものがあることを知る。
Integerクラスのキャッシュとは
ドキュメント
を見てみる。
(Javaバージョン: 24)

This method will always cache values in the range -128 to 127, inclusive
-128~127の範囲は常にキャッシュされるとのこと。
and may cache other values outside of this range.
ただし、範囲は-128~127ではないときもあるらしい。
どういうときに範囲が変わるのか気になったので調べた↓
キャッシュ範囲を深ぼる
コード を見てみると以下のとおりだった。
// high value may be configured by property
int h = 127;
String integerCacheHighPropValue =
VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
if (integerCacheHighPropValue != null) {
try {
h = Math.max(parseInt(integerCacheHighPropValue), 127);
// Maximum array size is Integer.MAX_VALUE
h = Math.min(h, Integer.MAX_VALUE - (-low) -1);
} catch( NumberFormatException nfe) {
// If the property cannot be parsed into an int, ignore it.
}
}
high = h;
java.lang.Integer.IntegerCache.high
というプロパティで、
キャッシュ範囲の上限値だけは変更できる。
結論
Integerクラスのキャッシュ範囲は以下のとおり。
- デフォルトでは-128~127の範囲の値をキャッシュ
java.lang.Integer.IntegerCache.high
プロパティを設定することで、上限値(high
)を127より大きい値に変更可能- 下限値(
low
)は常に-128
このキャッシュ機構を理解しておくことで、
パフォーマンスだけでなくIntegerクラスの同一性(==
による比較結果)の挙動についても正しく理解できる。