Compare two objects in Java with possible null values

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

    Since version 3.5 Apache Commons StringUtils has the following methods:

    static int  compare(String str1, String str2)
    static int  compare(String str1, String str2, boolean nullIsLess)
    static int  compareIgnoreCase(String str1, String str2)
    static int  compareIgnoreCase(String str1, String str2, boolean nullIsLess)
    

    These provide null safe String comparison.

提交回复
热议问题