【JDK源码学习】String

【JDK源码学习】String

如果饿了就吃,困了就睡,渴了就喝,人生就太无趣了
刚刚毕业,发现源码阅读的重要性,开始学习源码!欢迎大佬指正!!


1.介绍

String类使用final关键字修饰,所以不能被继承,也不能被修改,所以String类型是线程安全的。

2.重要属性

    /** The value is used for character storage. */
    private final char value[];

    /** Cache the hash code for the string */
    private int hash; // Default to 0

3.构造方法

	public String()
    public String(String original)
    public String(char value[])
    public String(char value[], int offset, int count)
    public String(int[] codePoints, int offset, int count)
	@Deprecated
    public String(byte ascii[], int hibyte, int offset, int count)
	@Deprecated
    public String(byte ascii[], int hibyte)
    public String(byte bytes[], int offset, int length, String charsetName) throws UnsupportedEncodingException
    public String(byte bytes[], int offset, int length, Charset charset)
    public String(byte bytes[], String charsetName) throws UnsupportedEncodingException
    public String(byte bytes[], Charset charset)
    public String(byte bytes[], int offset, int length)
    public String(byte bytes[])
    public String(StringBuffer buffer)
    public String(StringBuilder builder)

3.1 空的构造器

	/**
     * Initializes a newly created {@code String} object so that it represents
     * an empty character sequence.  Note that use of this constructor is
     * unnecessary since Strings are immutable.
     */
    public String() {
        this.value = "".value;
    }

该构造方法会创建空的对象,因此不建议下面这样创建String:

String str = new String();
str = "String ";

使用Debug看看存储情况:

  1. 使用new后,赋值前,@后面的相对地址为532
    在这里插入图片描述
  2. 赋值之后,@后面的相对地址改为了534,可以看出,st在赋值后指向了新的地址。
    在这里插入图片描述

3.2 字符串创建对象

    public String(String original) {
        this.value = original.value;
        this.hash = original.hash;
    }

直接将入参中的String 的 value和hash两个属性赋给目标String。查看下面代码的内存情况:a,b,c,d都指向同一个地址。

String a = "abc";
String b = new String("abc");
String c = new String(a);
String d = a;

在这里插入图片描述

3.3 字符数组创建字符串

	public String(char value[]) {
        this.value = Arrays.copyOf(value, value.length);
    }

	public String(char value[], int offset, int count) {
        if (offset < 0) {
            throw new StringIndexOutOfBoundsException(offset);
        }
        if (count <= 0) {
            if (count < 0) {
                throw new StringIndexOutOfBoundsException(count);
            }
            if (offset <= value.length) {
                this.value = "".value;
                return;
            }
        }
        // Note: offset or count might be near -1>>>1.
        if (offset > value.length - count) {
            throw new StringIndexOutOfBoundsException(offset + count);
        }
        this.value = Arrays.copyOfRange(value, offset, offset+count);
    }	

使用字符数组创建字符串有两个方法,这两方法都分别调用了Arrays.copyOfArrays.copyOfRange方法,都是将字符数组逐一复制到String的字符数组中。

3.4 使用字节数组构建字符串

使用字节数组的构造器有6个方法:

public String(byte bytes[]) {
	this(bytes, 0, bytes.length);
}

public String(byte bytes[], int offset, int length) {
	checkBounds(bytes, offset, length);
	this.value = StringCoding.decode(bytes, offset, length);
}

public String(byte bytes[], Charset charset) {
	this(bytes, 0, bytes.length, charset);
}

public String(byte bytes[], String charsetName)
            throws UnsupportedEncodingException {
	this(bytes, 0, bytes.length, charsetName);
}

public String(byte bytes[], int offset, int length, Charset charset) {
	if (charset == null)
		throw new NullPointerException("charset");
	checkBounds(bytes, offset, length);
	this.value =  StringCoding.decode(charset, bytes, offset, length);
}

public String(byte bytes[], int offset, int length, String charsetName) throws UnsupportedEncodingException {
	if (charsetName == null)
		throw new NullPointerException("charsetName");
	checkBounds(bytes, offset, length);
	this.value = StringCoding.decode(charsetName, bytes, offset, length);
}

因为byte数组和String转化要涉及编码,例如最后两个方法需入参给出编码对象Charset或者编码名称,之后都会调用StringCoding.decode()方法,进行解码。
第二个方法调用的StringCoding.decode()没有给出编码方式,但是观察一下这个方法的源码:默认的是ISO-8859-1的方法。

	static char[] decode(byte[] ba, int off, int len) {
        String csn = Charset.defaultCharset().name();
        try {
            // use charset name decode() variant which provides caching.
            return decode(csn, ba, off, len);
        } catch (UnsupportedEncodingException x) {
            warnUnsupportedCharset(csn);
        }
        try {
            return decode("ISO-8859-1", ba, off, len);
        } catch (UnsupportedEncodingException x) {
            // If this code is hit during VM initialization, MessageUtils is
            // the only way we will be able to get any kind of error message.
            MessageUtils.err("ISO-8859-1 charset not available: "
                             + x.toString());
            // If we can not find ISO-8859-1 (a required encoding) then things
            // are seriously wrong with the installation.
            System.exit(1);
            return null;
        }
    }

4.常用方法

4.1 length()

返回字符串的长度。直接返回字符数组的长度

    public int length() {
        return value.length;
    }

4.2 isEmpty()

判断字符串是否为空。

	public boolean isEmpty() {
        return value.length == 0;
    }

4.3 charAt()

返回对应位置的字符

 	public char charAt(int index) {
        if ((index < 0) || (index >= value.length)) {
            throw new StringIndexOutOfBoundsException(index);
        }
        return value[index];
    }

4.4 getBytes()

和使用byte数组构建String的构造方法相反,这个方法是将string转化为byte数组,这之间一定涉及编码的问题,这个方法有3个重载方法,

    public byte[] getBytes(String charsetName)
            throws UnsupportedEncodingException {
        if (charsetName == null) throw new NullPointerException();
        return StringCoding.encode(charsetName, value, 0, value.length);
    }

    public byte[] getBytes(Charset charset) {
        if (charset == null) throw new NullPointerException();
        return StringCoding.encode(charset, value, 0, value.length);
    }

    public byte[] getBytes() {
        return StringCoding.encode(value, 0, value.length);
    }

4.3 equals()

比较对象是否相相等

    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;
    }
  • 使用==先比较两个对象是否是同一个对象,是同一个直接返回true
  • 如果比较的对象不是同一个对象,接着判断比较的对象的是不是String类型,如果不是,直接返回false,如果是,接着比较value数组每个字符是否相同。

4.4 contentEquals()

比较参数的值是否相等

  • 这个可以有两个入参,StringBuliderCharSequence
  • 当入参是String类型,调用equals()方法
  • 其他类型都是比较内容是否相等
	public boolean contentEquals(StringBuffer sb) {
		return contentEquals((CharSequence)sb);
	}


	public boolean contentEquals(CharSequence cs) {
        // Argument is a StringBuffer, StringBuilder
        if (cs instanceof AbstractStringBuilder) {
            if (cs instanceof StringBuffer) {
                synchronized(cs) {
                   return nonSyncContentEquals((AbstractStringBuilder)cs);
                }
            } else {
                return nonSyncContentEquals((AbstractStringBuilder)cs);
            }
        }
        // Argument is a String
        if (cs instanceof String) {
            return equals(cs);
        }
        // Argument is a generic CharSequence
        char v1[] = value;
        int n = v1.length;
        if (n != cs.length()) {
            return false;
        }
        for (int i = 0; i < n; i++) {
            if (v1[i] != cs.charAt(i)) {
                return false;
            }
        }
        return true;
    }
	
	//私有方法
	private boolean nonSyncContentEquals(AbstractStringBuilder sb) {
        char v1[] = value;
        char v2[] = sb.getValue();
        int n = v1.length;
        if (n != sb.length()) {
            return false;
        }
        for (int i = 0; i < n; i++) {
            if (v1[i] != v2[i]) {
                return false;
            }
        }
        return true;
    }

4.5 equalsIgnoreCase()

不区分大小写比较。这个三元运算符省去了很多if,太妙了

    public boolean equalsIgnoreCase(String anotherString) {
        return (this == anotherString) ? true
                : (anotherString != null)
                && (anotherString.value.length == value.length)
                && regionMatches(true, 0, anotherString, 0, value.length);
    }

4.6 compareTo()

	public int compareTo(String anotherString) {
        int len1 = value.length;
        int len2 = anotherString.value.length;
        int lim = Math.min(len1, len2);
        char v1[] = value;
        char v2[] = anotherString.value;

        int k = 0;
        while (k < lim) {
            char c1 = v1[k];
            char c2 = v2[k];
            if (c1 != c2) {
                return c1 - c2;
            }
            k++;
        }
        return len1 - len2;
    }

根据字典顺序去比较两个字符串中第一个不相等的字符相差的距离。
例如:

	public static void main(String[] args) {
        String a = "abc";
        String b = "afg";
        System.out.println(a.compareTo(b));
    }

运行结构如下:第一个字符都是a,比较第二字符,b的ASCII码是98,f是104,相差-4。

在这里插入图片描述

4.7 compareToIgnoreCase()

忽略大小写比较

	public int compareToIgnoreCase(String str) {
        return CASE_INSENSITIVE_ORDER.compare(this, str);
    }
	public static final Comparator<String> CASE_INSENSITIVE_ORDER
                                         = new CaseInsensitiveComparator();
    private static class CaseInsensitiveComparator
            implements Comparator<String>, java.io.Serializable {
        // use serialVersionUID from JDK 1.2.2 for interoperability
        private static final long serialVersionUID = 8575799808933029326L;

        public int compare(String s1, String s2) {
            int n1 = s1.length();
            int n2 = s2.length();
            int min = Math.min(n1, n2);
            for (int i = 0; i < min; i++) {
                char c1 = s1.charAt(i);
                char c2 = s2.charAt(i);
                if (c1 != c2) {
                    c1 = Character.toUpperCase(c1);
                    c2 = Character.toUpperCase(c2);
                    if (c1 != c2) {
                        c1 = Character.toLowerCase(c1);
                        c2 = Character.toLowerCase(c2);
                        if (c1 != c2) {
                            // No overflow because of numeric promotion
                            return c1 - c2;
                        }
                    }
                }
            }
            return n1 - n2;
        }

        /** Replaces the de-serialized object. */
        private Object readResolve() { return CASE_INSENSITIVE_ORDER; }
    }

4.8 regionMatches()

区域进行比较,有两个重载方法,一个区分大小写进行比较内容是否相等。另一个是不区分大小写进行比较。

	public boolean regionMatches(int toffset, String other, int ooffset,
            int len) {
        char ta[] = value;
        int to = toffset;
        char pa[] = other.value;
        int po = ooffset;
        // Note: toffset, ooffset, or len might be near -1>>>1.
        if ((ooffset < 0) || (toffset < 0)
                || (toffset > (long)value.length - len)
                || (ooffset > (long)other.value.length - len)) {
            return false;
        }
        while (len-- > 0) {
            if (ta[to++] != pa[po++]) {
                return false;
            }
        }
        return true;
    }

	public boolean regionMatches(boolean ignoreCase, int toffset,
            String other, int ooffset, int len) {
        char ta[] = value;
        int to = toffset;
        char pa[] = other.value;
        int po = ooffset;
        // Note: toffset, ooffset, or len might be near -1>>>1.
        if ((ooffset < 0) || (toffset < 0)
                || (toffset > (long)value.length - len)
                || (ooffset > (long)other.value.length - len)) {
            return false;
        }
        while (len-- > 0) {
            char c1 = ta[to++];
            char c2 = pa[po++];
            if (c1 == c2) {
                continue;
            }
            if (ignoreCase) {
                // If characters don't match but case may be ignored,
                // try converting both characters to uppercase.
                // If the results match, then the comparison scan should
                // continue.
                char u1 = Character.toUpperCase(c1);
                char u2 = Character.toUpperCase(c2);
                if (u1 == u2) {
                    continue;
                }
                // Unfortunately, conversion to uppercase does not work properly
                // for the Georgian alphabet, which has strange rules about case
                // conversion.  So we need to make one last check before
                // exiting.
                if (Character.toLowerCase(u1) == Character.toLowerCase(u2)) {
                    continue;
                }
            }
            return false;
        }
        return true;
    }

4.9 startWith(),endwith()

startWith()两个重载方法,一个是从指定位置比较是否有相同的前缀,另一个是从开始比较是否有前缀。
endwith()是判断是否有相同的后缀,但是调用的方法依然 是startWith()

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

	public boolean endsWith(String suffix) {
        return startsWith(suffix, value.length - suffix.value.length);
    }

看个例子:

    public static void main(String[] args) {
        String a = "hello abc";
        String b = "hello afff";
        System.out.println(a.startsWith("abc", 5));
        System.out.println(a.startsWith("abc", 6));
        System.out.println(b.startsWith("hello"));
        System.out.println(b.endsWith("afff"));
    }

运行结果如下:
在这里插入图片描述

4.10 hashCode()

hashCode的数学公式:

s[0] * 31^(n-1) + s[1] * 31^(n-2) + ... + s[n-1]

第一次创建字符串会在hash字段添加该值,之后再调用直接返回该数值。

	public int hashCode() {
        int h = hash;
        if (h == 0 && value.length > 0) {
            char val[] = value;

            for (int i = 0; i < value.length; i++) {
                h = 31 * h + val[i];
            }
            hash = h;
        }
        return h;
    }

字符串哈希可以做很多事情,通常是类似于字符串判等,判回文之类的。

但是仅仅依赖于哈希值来判断其实是不严谨的,除非能够保证不会有哈希冲突,通常这一点很难做到。

就拿jdk中String类的哈希方法来举例,字符串"gdejicbegh"与字符串"hgebcijedg"具有相同的hashCode()返回值-801038016,并且它们具有reverse的关系。这个例子说明了用jdk中默认的hashCode方法判断字符串相等或者字符串回文,都存在反例

	public static void main(String[] args) {
        String a = "gdejicbegh";
        String b = "hgebcijedg";
        System.out.println(a.hashCode());
        System.out.println(b.hashCode());

    }

运行结果:
在这里插入图片描述

hashCode 可以保证相同的字符串的 hash 值肯定相同,但是 hash 值相同并不一定是 value 值就相同。

4.11 indexOf() lastIndexOf()

两个方法都有很多重载方法
indexOf()返回给定字符或者字符串与字符串第一个匹配字符或字符串的位置。

//判断字符
public int indexOf(int ch) {
    return indexOf(ch, 0);
}

public int indexOf(int ch, int fromIndex) {
    final int max = value.length;
    if (fromIndex < 0) {
        fromIndex = 0;
    } else if (fromIndex >= max) {
        // Note: fromIndex might be near -1>>>1.
        return -1;
    }
    if (ch < Character.MIN_SUPPLEMENTARY_CODE_POINT) {
        // handle most cases here (ch is a BMP code point or a
        // negative value (invalid code point))
        final char[] value = this.value;
        for (int i = fromIndex; i < max; i++) {
            if (value[i] == ch) {
                return i;
            }
        }
        return -1;
    } else {
        return indexOfSupplementary(ch, fromIndex);
    }
}

private int indexOfSupplementary(int ch, int fromIndex) {
    if (Character.isValidCodePoint(ch)) {
        final char[] value = this.value;
        final char hi = Character.highSurrogate(ch);
        final char lo = Character.lowSurrogate(ch);
        final int max = value.length - 1;
        for (int i = fromIndex; i < max; i++) {
            if (value[i] == hi && value[i + 1] == lo) {
                return i;
            }
        }
    }
    return -1;
}

//判断字符串
public int indexOf(String str) {
    return indexOf(str, 0);
}

public int indexOf(String str, int fromIndex) {
    return indexOf(value, 0, value.length,
            str.value, 0, str.value.length, fromIndex);
}

static int indexOf(char[] source, int sourceOffset, int sourceCount,
        String target, int fromIndex) {
    return indexOf(source, sourceOffset, sourceCount,
                   target.value, 0, target.value.length,
                   fromIndex);
}


static int indexOf(char[] source, int sourceOffset, int sourceCount,
        char[] target, int targetOffset, int targetCount,
        int fromIndex) {
    if (fromIndex >= sourceCount) {
        return (targetCount == 0 ? sourceCount : -1);
    }
    if (fromIndex < 0) {
        fromIndex = 0;
    }
    if (targetCount == 0) {
        return fromIndex;
    }
    char first = target[targetOffset];
    int max = sourceOffset + (sourceCount - targetCount);
    for (int i = sourceOffset + fromIndex; i <= max; i++) {
        /* Look for first character. */
        if (source[i] != first) {
            while (++i <= max && source[i] != first);
        }
        /* Found first character, now look at the rest of v2 */
        if (i <= max) {
            int j = i + 1;
            int end = j + targetCount - 1;
            for (int k = targetOffset + 1; j < end && source[j]
                    == target[k]; j++, k++);
            if (j == end) {
                /* Found whole string. */
                return i - sourceOffset;
            }
        }
    }
    return -1;
}

lastIndexOf()返回给定字符或者字符串与字符串最后一个匹配字符或字符串的位置。

public int lastIndexOf(int ch) {
    return lastIndexOf(ch, value.length - 1);
}

public int lastIndexOf(int ch, int fromIndex) {
    if (ch < Character.MIN_SUPPLEMENTARY_CODE_POINT) {
        // handle most cases here (ch is a BMP code point or a
        // negative value (invalid code point))
        final char[] value = this.value;
        int i = Math.min(fromIndex, value.length - 1);
        for (; i >= 0; i--) {
            if (value[i] == ch) {
                return i;
            }
        }
        return -1;
    } else {
        return lastIndexOfSupplementary(ch, fromIndex);
    }
}


private int lastIndexOfSupplementary(int ch, int fromIndex) {
    if (Character.isValidCodePoint(ch)) {
        final char[] value = this.value;
        char hi = Character.highSurrogate(ch);
        char lo = Character.lowSurrogate(ch);
        int i = Math.min(fromIndex, value.length - 2);
        for (; i >= 0; i--) {
            if (value[i] == hi && value[i + 1] == lo) {
                return i;
            }
        }
    }
    return -1;
}


public int lastIndexOf(String str) {
    return lastIndexOf(str, value.length);
}

public int lastIndexOf(String str, int fromIndex) {
    return lastIndexOf(value, 0, value.length,
            str.value, 0, str.value.length, fromIndex);
}

static int lastIndexOf(char[] source, int sourceOffset, int sourceCount,
        String target, int fromIndex) {
    return lastIndexOf(source, sourceOffset, sourceCount,
                   target.value, 0, target.value.length,
                   fromIndex);
}

static int lastIndexOf(char[] source, int sourceOffset, int sourceCount,
        char[] target, int targetOffset, int targetCount,
        int fromIndex) {
    /*
     * Check arguments; return immediately where possible. For
     * consistency, don't check for null str.
     */
    int rightIndex = sourceCount - targetCount;
    if (fromIndex < 0) {
        return -1;
    }
    if (fromIndex > rightIndex) {
        fromIndex = rightIndex;
    }
    /* Empty string always matches. */
    if (targetCount == 0) {
        return fromIndex;
    }
    int strLastIndex = targetOffset + targetCount - 1;
    char strLastChar = target[strLastIndex];
    int min = sourceOffset + targetCount - 1;
    int i = min + fromIndex;
startSearchForLastChar:
    while (true) {
        while (i >= min && source[i] != strLastChar) {
            i--;
        }
        if (i < min) {
            return -1;
        }
        int j = i - 1;
        int start = j - (targetCount - 1);
        int k = strLastIndex - 1;
        while (j > start) {
            if (source[j--] != target[k--]) {
                i--;
                continue startSearchForLastChar;
            }
        }
        return start - sourceOffset + 1;
    }
}

4.12 substring()

截取字符串。
有两个重载方法,一个给出子串的开始位置,一直截取到最后。

public String substring(int beginIndex) {
    if (beginIndex < 0) {
        throw new StringIndexOutOfBoundsException(beginIndex);
    }
    int subLen = value.length - beginIndex;
    if (subLen < 0) {
        throw new StringIndexOutOfBoundsException(subLen);
    }
    return (beginIndex == 0) ? this : new String(value, beginIndex, subLen);
}

另一个是给出子串的开始和结尾位置。

public String substring(int beginIndex, int endIndex) {
    if (beginIndex < 0) {
        throw new StringIndexOutOfBoundsException(beginIndex);
    }
    if (endIndex > value.length) {
        throw new StringIndexOutOfBoundsException(endIndex);
    }
    int subLen = endIndex - beginIndex;
    if (subLen < 0) {
        throw new StringIndexOutOfBoundsException(subLen);
    }
    return ((beginIndex == 0) && (endIndex == value.length)) ? this
            : new String(value, beginIndex, subLen);
}

subSequence(int beginIndex,int endIndex)是实现CharSequence接口的方法,具体做法和substring()一样。


public CharSequence subSequence(int beginIndex, int endIndex) {
    return this.substring(beginIndex, endIndex);
}

4.13 concat()

拼接字符串。利用Arrays.copyOf()函数进行字符数组的拼接。最后返回一个新的字符串。

public String concat(String str) {
    int otherLen = str.length();
    if (otherLen == 0) {
        return this;
    }
    int len = value.length;
    char buf[] = Arrays.copyOf(value, len + otherLen);
    str.getChars(buf, len);
    return new String(buf, true);
}

4.14 replace() replaceFirst() replaceAll()

replace()有两个重载方法:
第一个是替换字符:

public String replace(char oldChar, ch
    if (oldChar != newChar) {
        int len = value.length;
        int i = -1;
        char[] val = value; /* avoid g
        while (++i < len) {
            if (val[i] == oldChar) {
                break;
            }
        }
        if (i < len) {
            char buf[] = new char[len]
            for (int j = 0; j < i; j++
                buf[j] = val[j];
            }
            while (i < len) {
                char c = val[i];
                buf[i] = (c == oldChar
                i++;
            }
            return new String(buf, tru
        }
    }
    return this;
}

第二个是替换字符串:入参是有序字符

	public String replace(CharSequence target, CharSequence replacement) {
        return Pattern.compile(target.toString(), Pattern.LITERAL).matcher(
                this).replaceAll(Matcher.quoteReplacement(replacement.toString()));
    }

replaceFirst()替换字符串中的第一个相同的子串。

public String replaceFirst(String regex, String replacement) {
    return Pattern.compile(regex).matcher(this).replaceFirst(replacement);
}

replaceAll()替换所有相同的子串

public String replaceAll(String regex, String replacement) {
    return Pattern.compile(regex).matcher(this).replaceAll(replacement);
}

例子:

public static void main(String[] args) {
    String a = "gdafafgd";
    System.out.println(a.replace('g', 'z'));
    System.out.println(a.replace("af", "zz"));
    System.out.println(a.replaceFirst("a", "b"));
    System.out.println(a.replaceAll("af", "aaa"));
}

运行结果如下:
在这里插入图片描述

4.15 其他方法

toCharArray() 转化成字符数组
trim()去掉两端空格
toUpperCase()转化为大写
toLowerCase()转化为小写
valueOf()将不同的类型的对象转换为String
split()按照给定字符串将源字符串分成数组
intern()将字符串添加到`String 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章