如果我们在java中使用length()而不是equals()来检查空字符串,代码优化有什么区别吗??
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
}
Run Code Online (Sandbox Code Playgroud)
是真的吗??
您可以使用str.isEmpty(),它会在内部检查长度。
这是String该类的一个实现:
public int length() {
return count;
}
public boolean isEmpty() {
return count == 0;
}
Run Code Online (Sandbox Code Playgroud)
您可以看到isEmpty()将长度与 0 进行比较。
| 归档时间: |
|
| 查看次数: |
1703 次 |
| 最近记录: |