6
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【Java】equalsでfalseとなるのに==でtureとなるケースに注意

Last updated at Posted at 2017-03-09

同値関係について調べていたらJavaのequalsが出てきたのでメモ

  • == でfalse
  • equalsでtrue

になる場合はよく知っていると思う。
別のinstanceであり同値である場合の時です。

逆に

  • == でtrue
  • equalsでfalse

になるケースはあまり馴染みが無いと思う。

今回はその件に付いて検証。

環境:
Java1.8
Eclipse Neon.1

問題のソース

	@org.junit.Test
	public void test() {
		boolean b1 = 1 == 1.0;
		
		Integer i2 = 1;
		boolean b2 = i2==1.0;        //true
		boolean b3 = i2.equals(1.0); //false

		System.out.println(b2);
		System.out.println(b3);
		
		
	}

解説

double型の 1.0 をDouble型にauto boxingするためにDouble#valueOfが呼ばれます。

auto-boxing
    public static Double valueOf(double d) {
        return new Double(d);
    }

Double型に変換された1.0とInteger型の1とのequalsを使った比較になるのでfalseになります。

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

auto boxingには気をつけましょう。

auto boxing に関してはJava Puzzleでも同様の問題が出題されています。

auto boxing can give you what we call the surprise left jab

by Joshua Bloch

6
4
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
6
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?