Java null String equals result

后端 未结 8 742
星月不相逢
星月不相逢 2020-12-16 15:11

Please help me how does the string.equals in java work with null value? Is there some problem with exceptions? Three cases:

boolean result1,result2, result3;         


        
8条回答
  •  一个人的身影
    2020-12-16 15:26

    Indeed, you cannot use the dot operator on a null variable to call a non static method.

    Despite this, all depends on overriding the equals() method of the Object class. In the case of the String class, is:

    public boolean equals(Object anObject) {
        if (this == anObject) {
            return true;
        }
        if (anObject instanceof String) {
            String anotherString = (String)anObject;
            int n = count;
            if (n == anotherString.count) {
                char v1[] = value;
                char v2[] = anotherString.value;
                int i = offset;
                int j = anotherString.offset;
                while (n-- != 0) {
                    if (v1[i++] != v2[j++])
                        return false;
                }
                return true;
            }
        }
        return false;
    }
    

    If you pass null as parameter, both "if" will fail, returning false;

    An alternative for your case is to build a method for your requirements:

    public static boolean myEquals(String s1, String s2){
        if(s1 == null)
            return s2 == null;
        return s1.equals(s2);
    }
    

提交回复
热议问题