简体   繁体   English

Java 空字符串等于结果

[英]Java null String equals result

Please help me how does the string.equals in java work with null value?请帮助我 java 中的 string.equals 如何处理空值? Is there some problem with exceptions?异常有问题吗? Three cases:三种情况:

boolean result1,result2, result3;

    //1st case
    String string1 = null;
    String string2 = null;
    result = string1.equals(string2);
    //2nd case
    String string1 = "something";
    String string2 = null;
    result2 = string1.equals(string2);
    //3rd case 
    String string1 = null;
    String string2 = "something";
    result3 = string1.equals(string2);

What the values of results are?结果的价值是什么? I expect this values:我期望这个值:

result1 is true;结果 1 为真;
result2 is false;结果 2 为假;
result3 is false;结果 3 为假;

You cannot use the dereference (dot, '.') operator to access instance variables or call methods on an instance if that instance is null .如果实例为null ,则不能使用取消引用(点,'.')运算符访问实例变量或调用实例上的方法。 Doing so will yield a NullPointerException .这样做会产生NullPointerException

It is common practice to use something you know to be non-null for string comparison.通常的做法是使用您知道为非空的内容进行字符串比较。 For example, "something".equals(stringThatMayBeNull) .例如, "something".equals(stringThatMayBeNull)

Use Objects.equals() to compare strings, or any other objects if you're using JDK 7 or later.如果您使用的是 JDK 7 或更高版本,请使用Objects.equals()来比较字符串或任何其他对象。 It will handle nulls without throwing exceptions.它将处理空值而不抛出异常。 See more here: how-do-i-compare-strings-in-java在此处查看更多信息: how-do-i-compare-strings-in-java

And if you're not running JDK 7 or later you can copy the equals method from Objects like this:如果你没有运行 JDK 7 或更高版本,你可以像这样从Objects复制equals方法:

public static boolean equals(Object a, Object b) {
    return (a == b) || (a != null && a.equals(b));
}

Indeed, you cannot use the dot operator on a null variable to call a non static method.实际上,您不能在null变量上使用点运算符来调用非静态方法。

Despite this, all depends on overriding the equals() method of the Object class.尽管如此,一切都取决于覆盖Object类的equals()方法。 In the case of the String class, is:String类的情况下,是:

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 ;如果你传递null作为参数,两个“if”都会失败,返回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);
}

That piece of code will throw a NullPointerException whenever string1 is null and you invoke equals on it, as is the case when a method is implicitly invoked on any null object.每当 string1 为 null 并且您对其调用equals时,这段代码将抛出NullPointerException ,就像在任何 null 对象上隐式调用方法时的情况一样。

To check if a string is null, use == rather than equals .要检查字符串是否为空,请使用==而不是equals

Although result1 and result3 will not be set due to NullPointerExceptions, result2 would be false (if you ran it outside the context of the other results).尽管由于 NullPointerExceptions 而不会设置result1result3 ,但 result2 将为 false(如果您在其他结果的上下文之外运行它)。

You will get a NullPointerException in case 1 and case 3.在情况 1 和情况 3 中,您将获得 NullPointerException。

You cannot call any methods (like equals() ) on a null object.您不能在空对象上调用任何方法(如equals() )。

To prevent NPE while comparing Strings if at least one of them can be null, use StringUtils.equals method which is null-safe.如果至少有一个字符串可以为空,要在比较字符串时防止 NPE,请使用空安全的 StringUtils.equals 方法。

I am late to answer this, but you can use我来晚了回答这个问题,但你可以使用

StringUtils.equals(str1, str2)

if you are using spring如果你使用弹簧

We cannot use dot operator with null since doing so will give NullPointerException.我们不能对 null 使用点运算符,因为这样做会产生 NullPointerException。 Therefore we can take advantage of try..catch block in our program.因此我们可以在我们的程序中利用 try..catch 块。 This is a very crude way of solving your problem, but you will get desired output.这是解决问题的一种非常粗略的方法,但您会得到所需的输出。

try {
   result = string1.equals(string2);
} catch (NullPointerException ex) {
   result = string2 == null; //This code will be executed only when string 1 is null
}

Our most common use-case of this type of thing is when we have a database field that contains "Y" or "N" to represent a Boolean (it's an old system, don't ask).我们最常见的这种类型的用例是当我们有一个包含“Y”或“N”来表示布尔值的数据库字段时(这是一个旧系统,不要问)。

Thus, we do this:因此,我们这样做:

if ("Y".equals(stringObjectThatMayBeNull)? result: otherResult);

Instead of this:而不是这个:

if (stringObjectThatMayBeNull.equals("Y")? result: otherResult);

... which avoids a NullPointerException when executing the.equals method. ...在执行 the.equals 方法时避免了 NullPointerException。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM