0
1

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 3 years have passed since last update.

【Java】equalsメソッドで比較する方法まとめる

Posted at

プログラミング勉強日記

2020年11月11日
昨日の記事で【Java】==とequalsの違いという内容を扱った。今日は、equalsメソッドの大文字と小文字を区別せずに比較する方法やObjectsクラスのequalsメソッドでnullを比較する方法についてまとめる。

equalsメソッドとは(==との違い)

 2つの文字列が等しいかどうか比較する際に使う。int型やdouble型などのプリミティブ型の場合は==で比較するが、String型は参照型なのでequalsメソッドを用いて比較する。

public static void main(String[] args) {
    // String型変数のstr1とstr2を同じ文字列で初期化
    String str1 = "hello";
    String str2 = "hello";

    if(str1 == str2)
        System.out.println("1回目:str1=str2 (==で比較) ");
    else
        System.out.println("1回目:str1≠str2 (==で比較) ");

    // 同じ文字列を追加
    str1 += "!";
    str2 += "!";

    if(str1 == str2)
        System.out.println("2回目:str1=str2 (==で比較) ");
    else
        System.out.println("2回目:str1≠str2 (==で比較) ");

    if(str1.equals(str2))
        System.out.println("3回目:str1=str2 (equalsで比較) ");
    else
        System.out.println("3回目:str1≠str2 (equalsで比較) ");
}
実行結果
1回目:str1=str2 (==で比較) 
2回目:str1≠str2 (==で比較) 
3回目:str1=str2 (equalsで比較) 

 このコードでは==演算子を使った1回目の比較ではtrueを返しているが、文字列を追加した後の2回目の比較ではfalseを返している。equalsメソッドを使って比較した3回目はtrueを返している。このように、==演算子を使った場合は参照先の文字列が同じであってもオブジェクトが違うとfalseを返してしまうので、文字列を比較するためにはequalsメソッド使う。

大文字と小文字を区別しない比較する方法

 大文字と小文字を区別せずに、同じ文字列として比較したい場合にはequalsIgnoreCaseを使う。

public static void main(String[] args) {
    String str1 = "hello";
    String str2 = "HELLO";

    if(str1.equalsIgnoreCase(str2))
        System.out.println("str1=str2 ([equalsIgnoreCaseで比較) ");
    else
        System.out.println("str1≠str2 ([equalsIgnoreCaseで比較) ");

    if(str1.equals(str2))
        System.out.println("str1=str2 (equalsで比較) ");
    else
        System.out.println("str1≠str2 (equalsで比較) ");
}
実行結果
str1=str2 ([equalsIgnoreCaseで比較) 
str1≠str2 (equalsで比較) 

nullを安全に比較する方法

 Objectsクラスのequalsメソッドを使ってnullPointerExceptionの例外を発生させることなく安全に比較する。Stringクラスのequalsメソッドでは、メソッドの呼び出し元のオブジェクトがnullの場合にnullPointerExceptionの例外が発生する。
 まず、Objectsクラスのequalsメソッドを使うためにはjava.util.Objectsのインポートが必要である。

import java.util.Objects;
 
public class Main {
 
    public static void main(String[] args) {
 
        String str1 = null;
        String str2 = "abc";
        String str3 = null;
 
        System.out.println(Objects.equals(str1, str2));
        System.out.println(Objects.equals(str1, str3));
    }
}
実行結果
false
true

 このようにnull動詞を比較した場合にtrueを返せている。

参考文献

【速習Java】”==”と”equals”の違い(否定の方法も解説)
【Java入門】equalsメソッドで比較をする方法総まとめ

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?