LoginSignup
8
4

More than 5 years have passed since last update.

Javaのラッパークラスとプリミティブ型の同値比較

Posted at

とあるプロジェクトでラッパークラスとプリミティブ型の同値比較が誤っていたので、新人さんに向けに記事にしました。

DemoApp.java
public class DemoApp {

    public static void main(String[] args) {
        Integer x = 999999;
        Integer y = 999999;
        int z = 999999;

        // ラッパークラスの == 比較
        if (x == y) {
            System.out.println("same");
        } else {
            System.out.println("other");
        }

        // ラッパークラスの equals メソッドによる比較
        if (x.equals(y)) {
            System.out.println("same");
        } else {
            System.out.println("other");
        }

        // ラッパークラスとプリミティブ型の == 比較
        if (x == z) {
            System.out.println("same");
        } else {
            System.out.println("other");
        }

        // ラッパークラスとプリミティブ型の equals メソッドによる比較
        if (x.equals(z)) {
            System.out.println("same");
        } else {
            System.out.println("other");
        }
    }
}
実行結果
other
same
same
same

同じ数値のラッパークラスとプリミティブ型の変数を定義して同値比較した結果です。

項番 条件 結果
1 ラッパークラスとラッパークラスを==で同値比較 異なる
2 ラッパークラスとラッパークラスをequalsメソッドで同値比較 同じ
3 ラッパークラスとプリミティブ型を==で同値比較 同じ
4 ラッパークラスとプリミティブ型をequalsメソッドで同値比較 同じ

==は同じインスタンス(オブジェクト)を指し示すかどうかを判断するものですが、ラッパークラスとプリミティブ型でも同じと判断されるのは面白いですね。

8
4
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
4