length()代替equals()检验字符串是否为空串
来源:互联网 发布:深入理解nginx 百度云 编辑:程序博客网 时间:2024/06/05 23:56
主题
永远也不要使用string.equals(“”)检验一个字符串是空串
最优方案
检验字符串是空串的最好方法是:用length(),这个方法返回字符串中字符的个数,如果字符的个数是0,一定是空串。
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}
论证
String部分源码如下
length()
public int length() { return count;}
equals()方法源码
/** * Compares this string to the specified object. The result is {@code * true} if and only if the argument is not {@code null} and is a {@code * String} object that represents the same sequence of characters as this * object. * * @param anObject * The object to compare this {@code String} against * * @return {@code true} if the given object represents a {@code String} * equivalent to this string, {@code false} otherwise * * @see #compareTo(String) * @see #equalsIgnoreCase(String) */ public boolean equals(Object anObject) { if (this == anObject) { return true; } if (anObject instanceof String) { String anotherString = (String) anObject; int n = value.length; if (n == anotherString.value.length) { char v1[] = value; char v2[] = anotherString.value; int i = 0; while (n-- != 0) { if (v1[i] != v2[i]) return false; i++; } return true; } } return false; }
可以看出length()简单的返回字符的个数,不会浪费太多的CPU,但是equals()方法有很多的判断语句,还创建了临时数组和采用了循环,浪费了大量的CPU资源
java 6以后提供了 isEmpty()方法使用,所以以后用这个方法
/** * Returns <tt>true</tt> if, and only if, {@link #length()} is <tt>0</tt>. * * @return <tt>true</tt> if {@link #length()} is <tt>0</tt>, otherwise * <tt>false</tt> * * @since 1.6 */ public boolean isEmpty() { return value.length == 0; }
参考内容:click here
1 0
- length()代替equals()检验字符串是否为空串
- 如何判断字符串是否为空串?string.length的优越性
- 判断字符串是否为空 string != null && !string.equals("")
- 使用equals方法判断String字符串是否为空时报空指针错误
- 检验两个字符串是否为兄弟字符串
- 如何判断字符串是否为空串
- 如何判断字符串是否为空串?
- 验证字符串是否为空
- 判断字符串是否为空
- 判断是否为空字符串
- 判断字符串是否为空
- 判断字符串是否为空
- 判断字符串是否为空
- 判断字符串 是否为空
- 判断字符串是否为空
- 判断字符串是否为空
- 判断字符串是否为空
- 判断字符串是否为空
- 针对ns3所用bake的更新
- Objective-C Runtime 运行时之二:成员变量与属性
- HttpClient模拟表单传图片
- RESTful架构理解
- 如何定位Obj-C野指针随机Crash(二):让非必现Crash变成必现
- length()代替equals()检验字符串是否为空串
- 用两个栈实现队列
- Objective-C测试题
- 即时通讯系统及实现公共好友分组的方法
- 第3章 14
- 深入讲解WEBVIEW(上)
- jQuery验证控件jquery.validate.js使用说明+中文API
- 欢迎使用CSDN-markdown编辑器
- Flume Source--spooldir Sink--file_roll channels--file