【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 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章