length()代替equals()检验字符串是否为空串

主题
永远也不要使用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

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值