Java言語において、オートボクシング(autoboxing)により生成されるプリミティブ型ラッパークラス・インスタンスの同値性/同一性について。
注意:本記事は言語仕様の隅をつつく話題であり、大半のユースケースでequals
メソッドによる同値性判定が適切である。
プリミティブ型int
からラッパークラスjava.lang.Integer
へ変換する場合、インスタンス生成方法とその値に応じて同一性(identity)判定の結果が影響を受ける。なお、同値性(equality)については全パターンで期待通り同値と判定される。また下記コード★行の実行結果はJava言語仕様によって保証されるため、あらゆるJava実行環境*1で同じ結果が得られる。*2
// int型の値1000をInteger型へオートボクシング Integer x1 = 1000; Integer x2 = 1000; System.out.println(x1.equals(x2)); // 同値性: true System.out.println(x1 == x2); // 同一性: false(大抵は) // int型の値42をInteger型へオートボクシング Integer y1 = 42; Integer y2 = 42; System.out.println(y1.equals(y2)); // 同値性: true System.out.println(y1 == y2); // 同一性: true ★ // 値42をもつIntegerインスタンスを明示的に生成 Integer z1 = new Integer(42); Integer z2 = new Integer(42); System.out.println(z1.equals(z2)); // 同値性: true System.out.println(z1 == z2); // 同一性: false ★
この奇妙な振る舞いは、ボクシング変換(boxing conversion)の動作仕様において、一部の値(true
/false
や絶対値が小さな値)を特別扱いすることで生じる。通常のプログラムで常用されるプリミティブ型の値に対して、ラッパークラス・インスタンスの共用によりJVMメモリフットプリント抑制を目指した、Java言語仕様側からの要請事項となっている。Java Language Specification, Java SE 7 Editionより該当箇所を引用。
If the value
p
being boxed istrue
,false
, abyte
, or achar
in the range\u0000
to\u007f
, or anint
orshort
number between-128
and127
(inclusive), then letr1
andr2
be the results of any two boxing conversions ofp
. It is always the case thatr1 == r2
.Ideally, boxing a given primitive value p, would always yield an identical reference. In practice, this may not be feasible using existing implementation techniques. The rules above are a pragmatic compromise. The final clause above requires that certain common values always be boxed into indistinguishable objects. The implementation may cache these, lazily or eagerly. For other values, this formulation disallows any assumptions about the identity of the boxed values on the programmer's part. This would allow (but not require) sharing of some or all of these references.
This ensures that in most common cases, the behavior will be the desired one, without imposing an undue performance penalty, especially on small devices. Less memory-limited implementations might, for example, cache all char and short values, as well as int and long values in the range of -32K to +32K.
Chapter 5. Conversions and Promotions, 5.1.7. Boxing Conversion
関連URL