Board logo

标题: 深入【Java】底层细节知识点(3)String类的深入理解 [打印本页]

作者: look_w    时间: 2018-12-15 13:06     标题: 深入【Java】底层细节知识点(3)String类的深入理解

S
tring


了解一个类最好的方式就是看源码
public final class String    implements java.io.Serializable, Comparable<String>, CharSequence{    /** The value is used for character storage. */    private final char value[];    /** The offset is the first index of the storage that is used. */    private final int offset;    /** The count is the number of characters in the String. */    private final int count;    /** Cache the hash code for the string */    private int hash; // Default to 0    /** use serialVersionUID from JDK 1.0.2 for interoperability */    private static final long serialVersionUID = -6849794470754667710L;    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; /* avoid getfield opcode */        int off = offset;   /* avoid getfield opcode */        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 = (c == oldChar) ? newChar : c;            i++;        }        return new String(0, len, buf);        }    }    return this;}} 更多的不再展示。
从以上的源码中获得信息:
字符串常量池:





欢迎光临 电子技术论坛_中国专业的电子工程师学习交流社区-中电网技术论坛 (http://bbs.eccn.com/) Powered by Discuz! 7.0.0