4
2

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.

Stringのswitchがequalsで比較されることの確認

Last updated at Posted at 2016-09-19

厳密にはhashCodeが先に比較される。

SwitchSample.java
public class SwitchSample {
    public static void main(String[] args) {
        final String empty = "";
        final String newEmpty = new String("");

        //True
        System.out.println(newEmpty.equals(empty));
        //False
        System.out.println(newEmpty == empty);
        //True
        System.out.println(newEmpty.hashCode() == empty.hashCode());

        switch (newEmpty) {
        case empty:
            System.out.println("一致");
            break;
        default:
            System.out.println("不一致");
            break;
        }
    }
}
true
false
true
一致

参考
[mi_kami's diary : Java7のswitch文から得られるバイトコードの考察]
(http://mikamikuh.hatenablog.com/entry/2013/07/02/235156)

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?