Compare two objects in Java with possible null values

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

    boolean compare(String str1, String str2) {
        if(str1==null || str2==null) {
            //return false; if you assume null not equal to null
            return str1==str2;
        }
        return str1.equals(str2);
    }
    

    is this what you desired?

提交回复
热议问题