23
16

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] Enum の「equals」vs「==」(右の勝ち)

Posted at

結論だけ知りたい人のためにタイトルに結論を書いておきました。

Enumでは「equals」と「==」はどちらが強いのか

public void hoge(Code code) {
	
	// equalsの場合 〜〜
	if (Code.Success.equals(code)) {
		// 成功
	}

	// ==の場合 〜〜
	if (Code.Success == code) {
		// 成功
	}
}

enum Code {
	Error,
	Success,
}

結論

Enumのequalsの実装を見れば一目瞭然ですね

Enum.java
@Override
public final boolean equals(Object other) {
    return this == other;
}

[補足] == の方が強い理由その1

文字数比較.java
if (code.equals(Code.Success)) { }
if (code == Code.Success) { }
                          // 1   5文字少ない!!!
                          //  2 4
                          //   3

[補足] == の方が強い理由その2

ぬるぽ.java
Code code = null;

// NullPointerException発生
if (code.equals(Code.Success)) { }

// こっちは大丈夫
if (code == Code.Success) { }

[補足] == の方が強い理由その3

今時はLintが指摘してくれるからあまり意味は無いが……

コンパイル.java
String code = "Error";

// コンパイルが通ってしまう
if (Code.Success.equals(code)) { }

// コンパイルエラーになるのでバグの混入を防げる 
if (Code.Success == code) { }
23
16
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
23
16

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?