使用length()而不是equals()来检查Java中的空字符串 [英] length() instead of equals() to check empty string in java
本文介绍了使用length()而不是equals()来检查Java中的空字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我们使用length()而不是equals()来检查Java中的空字符串,则代码优化是否有任何区别?
Is there any difference in Code Optimization if we use use length() instead of equals() to check empty string in java??
public boolean isEmpty(String str)
{
return str.equals(""); //NEVER do this
}
public boolean isEmpty(String str)
{
return str.length()==0; //Correct way to check empty
}
是真的吗?
推荐答案
您可以使用str.isEmpty()
,它在内部检查长度.
You can use str.isEmpty()
, which internally checks the length.
这是String
类的实现:
public int length() {
return count;
}
public boolean isEmpty() {
return count == 0;
}
您可以看到isEmpty()
将长度与0进行比较.
You can see that isEmpty()
compares the length to 0.
这篇关于使用length()而不是equals()来检查Java中的空字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文