yohhoyの日記

技術的メモをしていきたい日記

オートボクシングと同一性比較の奇妙な振る舞い

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 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.

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

*1:もちろん、Java実行環境が厳格に言語仕様準拠することが前提。

*2:1つ目の例示で用いた値 1000 からのオートボクシング後インスタンスの同一性については、Java実行環境毎に結果が異なる可能性がある。これはJava言語仕様ではインスタンス共用を保証する最低要件のみを定義しており、その範囲を超える値をインスタンス共用するかは否かは処理系依存となるため。