ラッパークラスのキャッシング
基本データ型のラッパークラスのキャッシュが適用されるのは、ボクシング変換のときである。
Java Generics and Collections には次のような記述がある。
ということで、Java言語仕様 第3版を確認してみる。Caching is required when boxing an int or short value between -128 and 127, a char value between '\u0000' and '\u007f', a byte, or a boolean; and caching is permitted when boxing other values.
訳)-128 から 127 の int 値と short 値、'\u0000' から '\u007f' までの char 値、byte 値、boolean 値をボクシングする際には、キャッシングが要求されている。加えて、その他の値をボクシングする場合もキャッシュすることが許されている。
Java Generics and Collections — 1.2 boxing and Unboxing (P.8)
原文はボクシング変換の対象となる値 p が true, false, byte, \u0000 から \u007f までの範囲にある char, あるいは -128 から 127 までの数値となる int や short である場合,任意の p に対する2つのボクシング変換結果を r1 と r2 とする。この場合,常に r1 == r2 が成立する。
Java言語仕様 第3版 — 5.1.7 ボクシング変換
である。If the value p being boxed is true, false, a byte, or a char in the range \u0000 to \u007f, or an int or short number between -128 and 127 (inclusive), then let r1 and r2 be the results of any two boxing conversions of p. It is always the case that r1 == r2.
「If the value p being boxed is true, false, a byte,」は「ボクシング変換の対象となる値 p が true, false, byte値」と訳した方がよいだろう。
Java Generics and Collections の次の記述も興味深い。
実際に次のコードのアサーションが成功する。The call Integer.valueOf(1) is similar in effect to the expression new Integer(1), but may cache some values for improved performance, as we explain shortly.
訳)Integer.valueOf(1) の呼出しは、new Integer(1) の式と同様に作用しますが、パフォーマンス改善のため、いくつかの値をキャッシュします。
Java Generics and Collections — 1.2 boxing and Unboxing (P.7)
Integer n = 47; Integer m = 47; assert m == n; assert Integer.valueOf(47) == Integer.valueOf(47); assert new Integer(47) != new Integer(47);
キャッシュについてはこちらも参考になる。
数字のキャッシュ - きどたかのブログ
この記事によるとオートボクシングは valueOf メソッドの呼出しに置換されるそうだ。