我应该使用string.isEmpty()还是“" .equals(string)? [英] Should I use string.isEmpty() or "".equals(string)?

查看:131
本文介绍了我应该使用string.isEmpty()还是“" .equals(string)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

标题基本上都说明了一切。我通常在 string == null 旁边测试它,所以我并不真正关心一个零安全测试。我应该使用哪个?

The title basically says it all. I'm usually testing this alongside a string == null, so I'm not really concerned about a null-safe test. Which should I use?

String s = /* whatever */;
...
if (s == null || "".equals(s))
{
    // handle some edge case here
}

if (s == null || s.isEmpty())
{
    // handle some edge case here
}

在那个笔记上 - isEmpty()甚至做除以外的任何事情都会返回.equals(); 返回this.length()== 0;

On that note - does isEmpty() even do anything other than return this.equals(""); or return this.length() == 0;?

推荐答案

。equals(s)的主要好处是你不需要 null检查(等于将检查其参数并返回 false 如果它为null),你似乎不在乎关于。如果您不担心 s 为空(或以其他方式检查它),我肯定会使用 s.isEmpty();它显示你正在检查的内容,你关心 s 是否为空,而不是它是否等于空字符串

The main benefit of "".equals(s) is you don't need the null check (equals will check its argument and return false if it's null), which you seem to not care about. If you're not worried about s being null (or are otherwise checking for it), I would definitely use s.isEmpty(); it shows exactly what you're checking, you care whether or not s is empty, not whether it equals the empty string

这篇关于我应该使用string.isEmpty()还是“" .equals(string)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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