JDK源码-String

String这个类是将String 放入到char数组来实现功能的。 首先看一下三个全局变量

1.offset(偏移量) : 默认为0 
2. count(大小) : count为当前字符串转为char之后的数组长度。 arrayOfchar.Length 
3. value(char数组): arrayOfchar

方法一: isEmpty() 
源码:

public boolean isEmpty() {
    return count == 0;
}

很简单 isEmpty等价于array.length() == 0。 
所以说 准确的判断字符串相等 : Str != null && !Str.isEmpty() 。 
isEmpty应该是在所有字符串判断效率最高的 1.isEmpty 2.”“.equals() 3. str.length <= 0


方法二:equals() 
源码:

    public boolean equals(Object anObject) {
    if (this == anObject) {
       return true;
     }
    if (anObject instanceof String) {
        String anotherString = (String)anObject;
        int n = count;
        if (n == anotherString.count) {
            char v1[] = value;
            char v2[] = anotherString.value;
            int i = offset;
            int j = anotherString.offset;
            while (n-- != 0) {
                if (v1[i++] != v2[j++])
                return false;
            }
            return true;
        }
    }
    return false;
}

第一步判断是否为同一个对象,如果是则直接返回true。 
第二步通过instanceof 来判断是否为String类型,如果不是直接返回false。 
第三步判断长度。 
第四步将String转成char数组之后,一个字符一个字符进行比较,如果有一个不相等,则返回false。


方法三:compareTo() 
源码:

public int compareTo(String anotherString) {
    int len1 = count;
    int len2 = anotherString.count;
    int n = Math.min(len1, len2);
    char v1[] = value;
    char v2[] = anotherString.value;
    int i = offset;
    int j = anotherString.offset;
    if (i == j) {
       int k = i;
       int lim = n + i;
       while (k < lim) {
          char c1 = v1[k];
          char c2 = v2[k];
          if (c1 != c2) {
             return c1 - c2;
          }
          k++;
         }
    } else {
       while (n-- != 0) {
            char c1 = v1[i++];
            char c2 = v2[j++];
            if (c1 != c2) {
                  return c1 - c2;
            }
          }
    }
    return len1 - len2;
}

原理与equals相同,都是通过数组来实现,但是逻辑不同。我没有找到可以改变偏移位的方法,不知道else有什么用,不过既然写了,肯定有用,存在皆有道理嘛。它是取相同偏移位的进行逐个比较。如果不同则相减,就会出现正负数了。如果全部相等就是0。


方法四:startsWith()和endsWith() 
这两个方法在源码中实际上是调用的同一个方法。 
源码:

public boolean startsWith(String prefix) {
    return startsWith(prefix, 0);
}
public boolean endsWith(String suffix) {
    return startsWith(suffix, count - suffix.count);
}
public boolean startsWith(String prefix, int toffset) {
    char ta[] = value;
    int to = offset + toffset;
    char pa[] = prefix.value;
    int po = prefix.offset;
    int pc = prefix.count;
    // Note: toffset might be near -1>>>1.
    if ((toffset < 0) || (toffset > count - pc)) {
       return false;
    }
    while (--pc >= 0) {
        if (ta[to++] != pa[po++]) {
           return false;
        }
    }
    return true;
}

第二个参数是说要从哪个下边开始进行比较,没有这个参数时默认为0,endwith是从当前数组长度-指定字符长度开始进行比较。不相同就返回false

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值