Compare two objects in Java with possible null values

前端 未结 12 1528
忘掉有多难
忘掉有多难 2020-11-27 11:58

I want to compare two strings for equality when either or both can be null.

So, I can\'t simply call .equals() as it can contain null<

12条回答
  •  臣服心动
    2020-11-27 12:33

    You can use java.util.Objects as following.

    public static boolean compare(String str1, String str2) {
        return Objects.equals(str1, str2);
    }
    

提交回复
热议问题