Compare two objects in Java with possible null values

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

    This is what Java internal code uses (on other compare methods):

    public static boolean compare(String str1, String str2) {
        return (str1 == null ? str2 == null : str1.equals(str2));
    }
    

提交回复
热议问题