LoginSignup
3
1

More than 5 years have passed since last update.

== と equals の不思議な関係

Last updated at Posted at 2016-12-03
1 / 21

第一問


public class Test {
    public static void main(String[] args){
        Integer i = new Integer(1);
        Integer j = new Integer(1);

        System.out.printf("%b, %b\n", i.equals(j), (i == j));
    }   
}

上記のプログラムの実行結果は次のうちのどれ?

  1. true, true
  2. true, false
  3. false, true
  4. false, false

正解


2. true, false


解説


ここで "==" は「参照等値演算子」であり、ij はそれぞれ別のインスタンスの参照なので等値とはならない。
インスタンスの「値」が等しいかどうかを確かめたい場合は、equals メソッドを使用する。


まあこれは入門書や入門サイト的なものに必ずといいほど載っている、初心者のはまりポイント(最初は == を使いがち)である。


第二問


public class Test {
    public static void main(String[] args){
        Integer x = 1;

        System.out.printf("%b, %b\n", x.equals(1.0), (x == 1.0));
    }   
}

上記のプログラムの実行結果は次のうちのどれ?

  1. true, true
  2. true, false
  3. false, true
  4. false, false

正解


3. false, true


もしかして


== と equals が


入れ替わってるー!?


解説


x.equals(1.0) が false になるのは何故?


Integer#equals の仕様だから。

public boolean equals(Object obj) {
    if (obj instanceof Integer) {
        return value == ((Integer)obj).intValue();
    }
    return false;
}

こんな感じの実装になっていて、型があっていないと無条件で false です。


x == 1.0 が true になるのは何故?


x は Integer なのであるが、== による比較対象が数値リテラルなのでアンボクシングされてプリミティブな数値同士の比較になる。第一問の == とはそもそも別物なのである。
入れ替わってるのは ==equals じゃなくて、実は ==== なのでした。


終わり

3
1
0

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
3
1