简体   繁体   English

在Java中检查字符串/对象的空值?

[英]Checking null value for a String/Object in java?

What are the advantages of having 有什么好处

String a = null;
if(null != a)

over 过度

if(a !=null)

I tried both statement and they worked fine. 我尝试了两种说法,他们都很好。 Any suggestions why should I go with the first one? 有什么建议我为什么要选择第一个?

Both are the same, however if you are checking for == on a boolean value: 两者是相同的,但是如果要检查布尔值上的==

if(a == true)

vs

if(true == a)

The latter would be better due to the tendency of typographical error by typing only = instead of == : 通过仅键入=而不是==由于印刷错误的趋势,后者会更好:

if(a = true) //still compilable but not what you intended
if(true = a) //cannot be compiled, hence you know you typed it wrongly

It just sounds more natural to put the item under question first. 将问题放在第一位听起来更自然。

In English you would say, "if answer is correct then check". 用英语你会说:“如果答案正确,那就检查”。 You wouldn't say, "if correct is answer". 您不会说“如果是正确的答案”。 People code the way they think and speak. 人们以思考和说话的方式进行编码。

The only valid use case to switch the order (that I'm aware of) is where you're calling equals() but the object you're testing may be null. 切换顺序(我知道)的唯一有效用例是您在调用equals()但是您要测试的对象可能为null。 In such a case, it can be cleaner to do 在这种情况下,这样做可以更清洁

if ("expected".equals(value))

than

if (value != null && value.equals("expected"))

Advantage : Placing the constant value in the expression does not change the behavior of the program (unless the values evaluate to false). 优点:将常量值放在表达式中不会改变程序的行为(除非值评估为false)。 In programming languages that use a single equals sign (=) for assignment and not for comparison, a possible mistake is to assign a value unintentionally instead of writing a conditional statement. 在使用单个等号(=)进行赋值而不用于比较的编程语言中,可能的错误是无意中赋值而不是编写条件语句。

Performance: No impact on performace 绩效:不影响绩效

Readability: Its decreased 可读性:降低

Cons The advantage of avoiding null behavior can also be considered a disadvantage, as null pointer errors can be hidden and only appear much later in the program. 缺点避免空行为的优点也可以看作是一个缺点,因为空指针错误可以被隐藏,并且只会在程序的后面出现。

Well, nothing besides (the lack of) readability. 好吧,除了(缺乏)可读性之外,什么都没有。

Also, it only works with boolean types: 此外,它仅适用于布尔类型:

boolean b = true;
if (b) {
    System.out.println("b, it is"); // << this
} else {
    System.out.println("not b");
}

Let's hack: 让我们破解:

boolean b = false;
if (b = true) {
    System.out.println("b, it is"); // << this
} else {
    System.out.println("not b");
}

Other way around: 其他方法:

boolean b = true;
if (b = false) {
    System.out.println("b, it is");
} else {
    System.out.println("not b"); // << this
}

But with an int: 但是有一个int:

int a = 5;
if(a = 0) { // error: incompatible types: int cannot be converted to boolean
    System.out.println("0");
} else {
    System.out.println("not 0");
}

Same happens in your example, with a String and the a = null expression. 在您的示例中,使用String和a = null表达式的情况相同。 So while this Yoda Comparison is useful in C, it is useless in Java. 因此,尽管此Yoda比较在C中很有用,但在Java中却没有用。

It seems like there is a tiny difference. 似乎有微小的区别。 Using JMH there seems tiny difference between in the SecureRandom test and random test. 使用JMH,SecureRandom测试和随机测试之间似乎没有什么区别。 The difference is not significant in my opinion. 在我看来,差异并不明显。

Benchmark                                                        Mode  Samples  Score  Score error   Units
c.g.v.YodaCompPerformace.countNullsArrayList                    thrpt      200  1.345        0.009  ops/ms
c.g.v.YodaCompPerformace.countNullsArrayListSecureRandom        thrpt      200  1.349        0.008  ops/ms
c.g.v.YodaCompPerformace.countNullsArrayListSecureRandomYoda    thrpt      200  1.358        0.009  ops/ms
c.g.v.YodaCompPerformace.countNullsArrayListYoda                thrpt      200  1.361        0.009  ops/ms

JHM code : JHM代码:

import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.Level;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;

@OutputTimeUnit(TimeUnit.MILLISECONDS)
@State(Scope.Thread)
public class YodaCompPerformace {

    static List<Integer> arrayListSecureRandom;
    static List<Integer> arrayListRandom;

    @Setup(Level.Iteration)
    public void setUpSecureRandom() {
        arrayListSecureRandom = new ArrayList<>(100000);
        for (int count = 0; count < 100000; count++) {
            if ((count & 1) == 0) {
                arrayListSecureRandom.add(count);
            } else {
                arrayListSecureRandom.add(null);
            }
        }
        Collections.shuffle(arrayListSecureRandom, new SecureRandom());
    }

    @Setup(Level.Iteration)
    public void setUp() {
        arrayListRandom = new ArrayList<>(100000);
        for (int count = 0; count < 100000; count++) {
            if ((count & 1) == 0) {
                arrayListRandom.add(count);
            } else {
                arrayListRandom.add(null);
            }
        }
        Collections.shuffle(arrayListRandom, new Random());
    }
    @Benchmark
    public int countNullsArrayListSecureRandom() {
        int countNulls = 0;
        for (Integer i : arrayListSecureRandom) {
            if (i == null) {
                countNulls++;
            }
        }
        return countNulls;
    }
    @Benchmark
    public int countNullsArrayListSecureRandomYoda() {
        int countNulls = 0;
        for (Integer i : arrayListSecureRandom) {
            if (null == i) {
                countNulls++;
            }
        }
        return countNulls;
    }
    @Benchmark
    public int countNullsArrayList() {
        int countNulls = 0;
        for (Integer i : arrayListSecureRandom) {
            if (i == null) {
                countNulls++;
            }
        }
        return countNulls;
    }
    @Benchmark
    public int countNullsArrayListYoda() {
        int countNulls = 0;
        for (Integer i : arrayListSecureRandom) {
            if (null == i) {
                countNulls++;
            }
        }
        return countNulls;
    }

}

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

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