2.1String类

2.1String类

 

想要了解一个类,最好的办法就是看这个类的实现源代码:

public final class String
    implements java.io.Serializable, Comparable<String>, CharSequence
{
    /** 该值用于字符存储 */
    private final char value[];
​
    /** 偏移量是所使用存储的第一个索引。 */
    private final int offset;
​
    /** 计数是字符串中的字符数。 */
    private final int count;
​
    /** 缓存字符串的哈希码 */
    private int hash; // 默认为0
​
    /** 使用JDK 1.0.2中的serialVersionUID实现互操作性 */
    private static final long serialVersionUID = -6849794470754667710L;
    ........
}

从上面可以看出几点:

1)String类时final类,也即以为着String类不能被继承,并且它的成员方法都默认为final方法。在Java中该类中的成员方法都默认为fianl方法。

2)上面列举出了String类中所有的成员属性,从上面可以看出String类其实是通过char数组来保存字符串的。

 

String类一些方法实现:

public String substring(int beginIndex, int endIndex) {
    if (beginIndex < 0) {
        throw new StringIndexOutOfBoundsException(beginIndex);
    }
    if (endIndex > count) {
        throw new StringIndexOutOfBoundsException(endIndex);
    }
    if (beginIndex > endIndex) {
        throw new StringIndexOutOfBoundsException(endIndex - beginIndex);
    }
    return ((beginIndex == 0) && (endIndex == count)) ? this :
        new String(offset + beginIndex, endIndex - beginIndex, value);
}
​
public String concat(String str) {
    int otherLen = str.length();
    if (otherLen == 0) {
        return this;
    }
    char buf[] = new char[count + otherLen];
    getChars(0, count, buf, 0);
    str.getChars(0, otherLen, buf, count);
    return new String(0, count + otherLen, buf);
}
​
public String replace(char oldChar, char newChar) {
    if (oldChar != newChar) {
        int len = count;
        int i = -1;
        char[] val = value; /* 避免getfield操作码 */
        int off = offset;   /* 避免getfield操作码 */
​
        while (++i < len) {
        if (val[off + i] == oldChar) {
            break;
        }
        }
        if (i < len) {
        char buf[] = new char[len];
        for (int j = 0 ; j < i ; j++) {
            buf[j] = val[off+j];
        }
        while (i < len) {
            char c = val[off + i];
            buf[i] = (c == oldChar) ? newChar : c;
            i++;
        }
        return new String(0, len, buf);
        }
    }
    return this;
}

从上面的三个方法可以看出,无论是substing、concat还是replace操作都不是在原有的字符串上进行的,而是重新生成一个新的字符串对象。也就是说进行这些操作后,最开始的字符串并没有被改变。

在这里要永远记住一点:“String对象以但被创建就是固定不变了,对String对象的任何改变都不影响到原对象,相关的任何change操作都会生成新的对象”。

 

博主github:https://github.com/ccy524946/theInterviewQuestions/blob/master/java%E4%B8%AD%E7%9A%84String/2.1String%E7%B1%BB.md

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值