在字符串字面量上调用equals [英] Calling equals on string literal

查看:108
本文介绍了在字符串字面量上调用equals的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是整理我的代码有一点,有这样:

  String saving = getValue 
if(saving!= null&& saving.equals(true)){
// do something
}
pre>

然后,我想到了去除对 null 的检查:

  if(true.equals(saving)){
// do something
}

这绝对有效,但是安全的我的意思是字符串字面量存储在一个公共池,而由 new 创建的字符串对象在堆上。但是常量池中的字符串也是对象,对吗?



但是,它似乎不是正确的做法,即使它使代码更短。 / p>

解决方案

这是安全的,正如你所看到的,一种避免空指针的好方法。



你提到使用 new 字符串。许多java静态代码分析工具将建议总是使用 new String(foo);





如果需要,您甚至可以使用:

  if(Boolean.valueOf(saving)){
...
}

根据 docs ,传递 null 将返回 false


I just was tidying my code a bit and there was this piece:

String saving = getValue();
if(saving != null && saving.equals("true")){
   // do something
}

Then I thought of doing it the other way around to get rid of the checking for null:

if("true".equals(saving)){
   // do something
}

It definitely works, but is this safe to do so? I mean string literals are stored in a common pool, while string object create by new are on the heap. But strings in the constant pool are also objects, right?

But still it doesn't seem like the right thing to do, even though it makes the code shorter.

解决方案

This is safe - and as you have seen, a good way of avoiding null pointers.

You mention the use of new for Strings. Many java static code analysis tools will recommend always using literals over new String("foo");.

Edit:

If you wanted, you could even just use:

if (Boolean.valueOf(saving)) {
    ...
}

According to the docs, passing null will return false.

这篇关于在字符串字面量上调用equals的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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