Java クラスObjectsのequalsメソッドで文字列とnullの比較サンプル

環境
JavaSE 1.8
Eclipse 4.14.0

構文
public static boolean equals(Object a,Object b)
引数が相互に等しい場合はtrueを返し、それ以外の場合はfalseを返します。したがって、両方の引数がnullの場合はtrueが返され、
1つの引数だけがnullの場合はfalseが返されます。それ以外の場合は、最初の引数のequalsメソッドを使用して等しいかどうかが判定されます。
パラメータ:
a – オブジェクト
b – aと等しいかどうかを比較するオブジェクト
戻り値:
引数が相互に等しい場合はtrue、それ以外の場合はfalse

使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
package com.arkgame.test;
import java.text.ParseException;
import java.util.Objects;
public class ArkTest {
public static void main(String[] args) throws ParseException {
String strA = "192.168.*";
String strB = "192.168.*";
// new演算子を使ってインスタンスを生成
String strD = new String("192.168.1");
String strE = null;
String strF = null;
System.out.println("nullと文字列Aの比較結果:" + Objects.equals(strE, strA));
System.out.println("nullの比較結果: " + Objects.equals(strE, strF));
System.out.println("文字列Aと文字列Bの比較結果: " + Objects.equals(strB, strA));
System.out.println("文字列Dと文字列Aの比較結果: " + Objects.equals(strD, strA));
}
}
package com.arkgame.test; import java.text.ParseException; import java.util.Objects; public class ArkTest { public static void main(String[] args) throws ParseException { String strA = "192.168.*"; String strB = "192.168.*"; // new演算子を使ってインスタンスを生成 String strD = new String("192.168.1"); String strE = null; String strF = null; System.out.println("nullと文字列Aの比較結果:" + Objects.equals(strE, strA)); System.out.println("nullの比較結果: " + Objects.equals(strE, strF)); System.out.println("文字列Aと文字列Bの比較結果: " + Objects.equals(strB, strA)); System.out.println("文字列Dと文字列Aの比較結果: " + Objects.equals(strD, strA)); } }
package com.arkgame.test;

import java.text.ParseException;
import java.util.Objects;

public class ArkTest {

      public static void main(String[] args) throws ParseException {
            String strA = "192.168.*";
            String strB = "192.168.*";

            // new演算子を使ってインスタンスを生成
            String strD = new String("192.168.1");
            String strE = null;
            String strF = null;

            System.out.println("nullと文字列Aの比較結果:" + Objects.equals(strE, strA));
            System.out.println("nullの比較結果: " + Objects.equals(strE, strF));
            System.out.println("文字列Aと文字列Bの比較結果: " + Objects.equals(strB, strA));
            System.out.println("文字列Dと文字列Aの比較結果: " + Objects.equals(strD, strA));
      }

}

実行結果
nullと文字列Aの比較結果:false
nullの比較結果: true
文字列Aと文字列Bの比較結果: true
文字列Dと文字列Aの比較結果: false

Java

Posted by arkgame