Calling equals on string literal

后端 未结 8 1272
再見小時候
再見小時候 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条回答
  •  梦毁少年i
    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;
    }
    

提交回复
热议问题