Calling equals on string literal

后端 未结 8 1270
再見小時候
再見小時候 2020-12-29 04:32

I just was tidying my code a bit and there was this piece:

String saving = getValue();
if(saving != null && saving.equals(\"true\")){
   // do someth         


        
相关标签:
8条回答
  • 2020-12-29 05:21

    The format of putting the literal first avoids the potential NPE and will always be false for "literal".equals(null).

    This is because a "literal" expression always evaluates to a String object (and is thus never null) and String.equals(obj) checks to see if the other object is a null (via asinstanceof). An object is an object - no need to worry bout the "heap".

    It's good practice to have a null-guard in an equals implementation as null.equals(null) is not permissible: "The equals method implements an equivalence relation on non-null object references"

    Here is the String.equals the source (for OpenJDK):

    public boolean equals(Object anObject) {
        if (this == anObject) {
            return true;
        }
        if (anObject instanceof String) {
            // ..
        }
        return false;
    }
    
    0 讨论(0)
  • 2020-12-29 05:25

    This is safe - and as you have seen, a good way of avoiding null pointers.

    You mention the use of new for Strings. Many java static code analysis tools will recommend always using literals over new String("foo");.

    Edit:

    If you wanted, you could even just use:

    if (Boolean.valueOf(saving)) {
        ...
    }
    

    According to the docs, passing null will return false.

    0 讨论(0)
提交回复
热议问题