Compare two objects in Java with possible null values

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

    OK, so what does "best possible solution" mean?

    If you mean most readable, then all the possible solutions are pretty much equivalent for an experienced Java programmer. But IMO the most readable is this

     public boolean compareStringsOrNulls(String str1, String str2) {
         // Implement it how you like
     }
    

    In other words, hide the implementation inside a simple method that (ideally) can be inlined.

    (You could also "out-source" to a 3rd party utility library ... if you already use it in your codebase.)


    If you mean most performant, then:

    1. the most performant solution depends on the platform and the context,
    2. one of the "context" issues is the relative (dynamic) frequency of occurrence of null arguments,
    3. it probably doesn't matter which version is faster ... because the difference is probably too small to make a difference to the overall application performance, and
    4. if it does matter, the only way to figure out which is fastest ON YOUR PLATFORM is to try both versions and measure the difference.

提交回复
热议问题