如何在java中根据null检查字符串? [英] How to check a string against null in java?

查看:18
本文介绍了如何在java中根据null检查字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 java 中根据空值检查字符串?我正在使用

How can I check a string against null in java? I am using

stringname.equalsignorecase(null)

但它不起作用.

推荐答案

string == null 比较对象是否为空.string.equals("foo") 比较该对象内部的值.string == "foo" 并不总是有效,因为您试图查看对象是否相同,而不是它们所代表的值.

string == null compares if the object is null. string.equals("foo") compares the value inside of that object. string == "foo" doesn't always work, because you're trying to see if the objects are the same, not the values they represent.


更长的答案:


Longer answer:

如果您尝试此操作,它将不起作用,正如您所发现的:

If you try this, it won't work, as you've found:

String foo = null;
if (foo.equals(null)) {
    // That fails every time. 
}

原因是foo为null,所以不知道.equals是什么;那里没有可以调用 .equals 的对象.

The reason is that foo is null, so it doesn't know what .equals is; there's no object there for .equals to be called from.

您可能想要的是:

String foo = null;
if (foo == null) {
    // That will work.
}

在处理字符串时保护自己免受空值的典型方法是:

The typical way to guard yourself against a null when dealing with Strings is:

String foo = null;
String bar = "Some string";
...
if (foo != null && foo.equals(bar)) {
    // Do something here.
}

这样,如果 foo 为 null,它就不会评估条件的后半部分,一切正常.

That way, if foo was null, it doesn't evaluate the second half of the conditional, and things are all right.

如果您使用的是字符串文字(而不是变量),最简单的方法是:

The easy way, if you're using a String literal (instead of a variable), is:

String foo = null;
...
if ("some String".equals(foo)) {
    // Do something here.
}

如果你想解决这个问题,Apache Commons 有一个类 - StringUtils - 提供空安全的字符串操作.

If you want to work around that, Apache Commons has a class - StringUtils - that provides null-safe String operations.

if (StringUtils.equals(foo, bar)) {
    // Do something here.
}

另一个回应是在开玩笑,说你应该这样做:

Another response was joking, and said you should do this:

boolean isNull = false;
try {
    stringname.equalsIgnoreCase(null);
} catch (NullPointerException npe) {
    isNull = true;
}

请不要那样做.你应该只对异常的错误抛出异常;如果你期待一个空值,你应该提前检查它,而不是让它抛出异常.

Please don't do that. You should only throw exceptions for errors that are exceptional; if you're expecting a null, you should check for it ahead of time, and not let it throw the exception.

在我看来,这有两个原因.首先,异常很慢;检查 null 很快,但是当 JVM 抛出异常时,它需要很多时间.其次,如果你只是提前检查空指针,代码会更容易阅读和维护.

In my head, there are two reasons for this. First, exceptions are slow; checking against null is fast, but when the JVM throws an exception, it takes a lot of time. Second, the code is much easier to read and maintain if you just check for the null pointer ahead of time.

这篇关于如何在java中根据null检查字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆