Compare two objects in Java with possible null values

前端 未结 12 1536
忘掉有多难
忘掉有多难 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:22

    boolean compare(String str1, String str2) {
        if (str1 == null || str2 == null)
            return str1 == str2;
    
        return str1.equals(str2);
    }
    

提交回复
热议问题