String源碼閱讀

String源碼閱讀

wiki

學(xué)習(xí)目標(biāo)

  • String在內(nèi)存中存在形式;
    • intern的用法,不同版本實(shí)現(xiàn)的差異
  • String的基本用法;

內(nèi)存角度理解String

String str = new String("uranus"); // 堆中有String實(shí)例對(duì)象,常量池中有String實(shí)例

String str1 = "uranus"; //常量池中有string實(shí)例

String str2 = new String("uranus").intern(); //堆中有實(shí)例對(duì)象,常量池中有String實(shí)例對(duì)象

String str3 = "uranus" + "leon";//常量池中有uranusleon字符串的實(shí)例,沒有uranus和leon的實(shí)例

String str1 = "uranus";
String str4 = str1 + "leon";//堆中有uranusleon的實(shí)例,常量池中沒有uranusleon的實(shí)例,沒有l(wèi)eon的實(shí)例

String str5 = new String("uranus") + new String("leon"); // 堆中有uranus和leon的實(shí)例,在常量池中是否有uranusleon這個(gè)字符串

new String("uranusleon")

package StringTest;

public class StringBasic {
    public static void main(String[] args)
    {
        String s1 = "uranusleon";
        String s2 = new String("uranusleon");
        String s3 = new String("uranusleon").intern();

        System.out.println(s1 == s2); // false
        System.out.println(s1 == s3); // true
    }
}

new String()生成了幾個(gè)變量

若常量池中已經(jīng)存在字面量,則直接引用,也就是此時(shí)只會(huì)創(chuàng)建一個(gè)對(duì)象,如果常量池中不存在字面量,則先創(chuàng)建后引用,也就是有兩個(gè)

String字面量進(jìn)入字符串常量池的時(shí)機(jī)

  • new String(“字面量”) 中 “字面量” 是何時(shí)進(jìn)入字符串常量池的?

  • HotSpot VM的實(shí)現(xiàn)來說,加載類的時(shí)候,那些字符串字面量會(huì)進(jìn)入到當(dāng)前類的運(yùn)行時(shí)常量池,不會(huì)進(jìn)入全局的字符串常量池 ;

  • ldc指令觸發(fā)lazy resolution動(dòng)作

    • 到當(dāng)前類的運(yùn)行時(shí)常量池(runtime constant pool,HotSpot VM里是ConstantPool + ConstantPoolCache)去查找該index對(duì)應(yīng)的項(xiàng)
    • 如果該項(xiàng)尚未resolve則resolve之,并返回resolve后的內(nèi)容。
    • 在遇到String類型常量時(shí),resolve的過程如果發(fā)現(xiàn)StringTable已經(jīng)有了內(nèi)容匹配的java.lang.String的引用,則直接返回這個(gè)引用;
    • 如果StringTable里尚未有內(nèi)容匹配的String實(shí)例的引用,則會(huì)在Java堆里創(chuàng)建一個(gè)對(duì)應(yīng)內(nèi)容的String對(duì)象,然后在StringTable記錄下這個(gè)引用,并返回這個(gè)引用出去。
  • 實(shí)驗(yàn)代碼

    package StringTest;
    
    public class StringBasic {
        public static void main(String[] args) throws Exception {
            String string = new String("uranusleon");
        }
    }
    
  • 字節(jié)碼編譯

    public static void main(java.lang.String[]) throws java.lang.Exception;
        descriptor: ([Ljava/lang/String;)V
        flags: ACC_PUBLIC, ACC_STATIC
        Code:
          stack=1, locals=2, args_size=1
             0: ldc           #2                  // String uranusleon
             2: astore_1
             3: return
          LineNumberTable:
            line 5: 0
            line 6: 3
          LocalVariableTable:
            Start  Length  Slot  Name   Signature
                0       4     0  args   [Ljava/lang/String;
                3       1     1 string   Ljava/lang/String;
        Exceptions:
          throws java.lang.Exception
    
    • ldc指令將在堆中創(chuàng)建一個(gè)堆中對(duì)應(yīng)于“uranusleon”的實(shí)例,在字符串常量池中記錄引用。

String.intern()的理解

intern()的作用

當(dāng)一個(gè)String實(shí)例調(diào)用intern()方法時(shí),Java查找常量池中是否有相同Unicode的字符串常量,如果有,則返回其的引用,如果沒有,則在常量池中增加一個(gè)Unicode等于str的字符串并返回它的引用;

public static void main(String[] args) {
    String s = new String("1");
    s.intern();
    String s2 = "1";
    System.out.println(s == s2);

    String s3 = new String("1") + new String("1");// 堆中創(chuàng)建對(duì)象“11”,String常量池中沒有“11”
    s3.intern(); //JDK6中在String常量池中新創(chuàng)建一個(gè)對(duì)象,JDK7中在String常量池中保存堆中對(duì)象的引用
    String s4 = "11"; //JDK6中S4是常量池中對(duì)象的引用,JDK7中s4是堆中對(duì)象的引用
    System.out.println(s3 == s4); //JDK6中s3!=s4,JDK7中s3 == s4
}

打印結(jié)果

  • jdk6 下false false
  • jdk7下false true
public static void main(String[] args) {
    String s = new String("1");
    String s2 = "1";
    s.intern();
    System.out.println(s == s2);

    String s3 = new String("1") + new String("1"); // 堆中創(chuàng)建對(duì)象“11”,String常量池中沒有“11”
    String s4 = "11"; //jdk6和jdk7都會(huì)在常量池中創(chuàng)建“11”的對(duì)象
    s3.intern(); // 發(fā)現(xiàn)常量池中有“11”,不需要新建或者保存堆中對(duì)象的引用
    System.out.println(s3 == s4);
}

打印結(jié)果

  • jdk6 下false false
  • jdk7下false false

原因

  • jdk7版本中將String常量池從Perm區(qū)移動(dòng)到了java heap區(qū)域;
  • String.intern()方法執(zhí)行時(shí),如果堆中存在對(duì)象,會(huì)直接在String常量池中保存對(duì)象的引用,不會(huì)重新創(chuàng)建新的對(duì)象;

intern()的使用時(shí)機(jī)

對(duì)于可能經(jīng)常使用的字符串,并且這些字符串在編譯期無法確定,只能在運(yùn)行期才可以確定,可以使用intern()將字符串加入字符串常量池。

static final int MAX = 1000 * 10000;
static final String[] arr = new String[MAX];

public static void main(String[] args) throws Exception {
    Integer[] DB_DATA = new Integer[10];
    Random random = new Random(10 * 10000);
    for (int i = 0; i < DB_DATA.length; i++) {
        DB_DATA[i] = random.nextInt();
    }
    long t = System.currentTimeMillis();
    for (int i = 0; i < MAX; i++) {
        //arr[i] = new String(String.valueOf(DB_DATA[i % DB_DATA.length]));
         arr[i] = new String(String.valueOf(DB_DATA[i % DB_DATA.length])).intern();
    }

    System.out.println((System.currentTimeMillis() - t) + "ms");
    System.gc();
}

intern()理解的要點(diǎn)

  • String str1 = new String("uranus") + new String("leon")執(zhí)行后,String intern1之前,字符串常量池中有沒有"uranusleon"字符串的引用;

    類的常量池中沒有“uranusleon”字面量,所以字符串常量池中沒有"uranusleon"字符串的引用

  • String str1 = new String("uranus") + new String("leon")String str1 = new String("uranusleon");的區(qū)別,單獨(dú)執(zhí)行后字符串常量池內(nèi)有哪些字符串;

    • String str1 = new String("uranus") + new String("leon")執(zhí)行后字符串常量池有'uranus'和'leon'的引用,沒有'uranusleon'的引用
    • String str1 = new String("uranusleon");執(zhí)行后字符串常量池有'uranusleon'的引用
  • intern()方法執(zhí)行時(shí)字符串常量池內(nèi)是否有對(duì)應(yīng)的字符串;

由上述講解可以看出,在判斷字符串的引用在字符串常量池中是否存在主要看class文件的常量池中是否存在字符串的字面量。

String + 的實(shí)現(xiàn)

  • String + 是通過StringBuilder實(shí)現(xiàn)的

  • String str3 = str1 + str2

    對(duì)于字符串拼接,如果有一個(gè)參數(shù)是變量,拼接是使用Stringbuilder.append,編譯期無法知道具體的字面量值,無法在字符串常量池中生成。

  • String str5 = "uranus" + "leon"

    對(duì)應(yīng)字符串拼接,如果兩個(gè)參數(shù)都是字面量,則直接編譯為拼接后的字符串,字符串常量池中會(huì)生產(chǎn)uranusleon。

String源碼

構(gòu)造方法

  • String是用字符數(shù)組char[]表示的

    /** The value is used for character storage. */
        private final char value[];
    
  • 使用字符數(shù)組構(gòu)造String

    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方法將字符數(shù)組的內(nèi)容復(fù)制到value[]
    • 可以只使用字符數(shù)組的一部分初始化String
    String(char[] value, boolean share) {
            // assert share : "unshared not supported";
            this.value = value;
        }
    
    • 此構(gòu)造方法參數(shù)share的作用是為了區(qū)分String(char[] value)方法;
    • 此方法構(gòu)造出來的String和參數(shù)傳過來的char[]共享一個(gè)數(shù)組;
    • 優(yōu)點(diǎn)
      • 性能好:直接將數(shù)組引用賦值,不需要復(fù)制數(shù)組內(nèi)容,速度快;
      • 共享數(shù)組節(jié)約內(nèi)存;
      • 由于方法是protected的,對(duì)于調(diào)用他的方法來說,由于無論是原字符串還是新字符串,其value數(shù)組本身都是String對(duì)象的私有屬性,從外部是無法訪問的,因此對(duì)兩個(gè)字符串來說都很安全。
  • 使用字符串構(gòu)造String

    public String(String original) {
            this.value = original.value;
            this.hash = original.hash;
        }
    
    • 直接將value和hash賦值給新String
  • 使用字節(jié)數(shù)組構(gòu)造String

    • byte是網(wǎng)絡(luò)傳輸或存儲(chǔ)的序列化形式。所以在很多傳輸和存儲(chǔ)的過程中需要將byte[]數(shù)組和String進(jìn)行相互轉(zhuǎn)化。
    String(byte bytes[]);
    String(byte bytes[], Charset charset);
    String(byte bytes[], int offset, int length);
    String(byte bytes[], int offset, int length, Charset charset);
    String(byte bytes[], int offset, int length, String charsetName);
    String(byte bytes[], String charsetName);
    
    • 調(diào)用構(gòu)造方法時(shí)需要指定編碼格式,如果不指定,默認(rèn)為ISO-8859-1
  • 使用StringBuilder和StringBuffer構(gòu)造字符串

    public String(StringBuffer buffer) {
            synchronized(buffer) {
                this.value = Arrays.copyOf(buffer.getValue(), buffer.length());
            }
        }
    
    public String(StringBuilder builder) {
            this.value = Arrays.copyOf(builder.getValue(), builder.length());
        }
    
    • 基本不會(huì)使用到,一般使用StringBuilder和StringBuffer的toString()方法。

比較方法

public boolean equals(Object anObject);
public boolean contentEquals(CharSequence cs);
public boolean contentEquals(StringBuffer sb);
public boolean equalsIgnoreCase(String anotherString);
public int compareTo(String anotherString);
public int compareToIgnoreCase(String str);
public boolean regionMatches(boolean ignoreCase, int toffset,
            String other, int ooffset, int len); //Tests if two string regions are equal.
public boolean regionMatches(int toffset, String other, int ooffset,int len);

equal()方法

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) { // value是私有的,怎么可以直接訪問?
                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;
    }
  • private是針對(duì)類來說的,同一個(gè)類內(nèi)可以訪問相同類其他實(shí)例的私有變量;

  • 代碼提高效率的方法

    字符串相同:地址相同;地址不同,但是內(nèi)容相同

    策略:將比較快速的部分(地址,比較對(duì)象類型)放在前面比較,速度慢的部分(比較字符數(shù)組)放在后面執(zhí)行。

contentEquals()方法

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;
    }
  • public boolean contentEquals(StringBuffer sb);實(shí)際調(diào)用了contentEquals(CharSequence cs)方法;

  • AbstractStringBuilderString都是接口CharSequence的實(shí)現(xiàn),通過判斷輸入是AbstractStringBuilder還是String的實(shí)例,執(zhí)行不同的方法;

  • 比較的核心代碼

    for (int i = 0; i < n; i++) {
                if (v1[i] != v2[i]) {
                    return false;
                }
            }
    
    • 對(duì)字符串的字符數(shù)組中字符依次進(jìn)行比較

equalsIgnoreCase(String anotherString)

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

compareTo()和compareToIgnoreCase()方法

  • 核心代碼是比較字符數(shù)組的每一個(gè)字符;
  • compareToIgnoreCase()方法使用String的內(nèi)部類CaseInsensitiveComparator;

Hashcode()方法

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;
    }

subString()方法

  • public String substring(int beginIndex, int endIndex);
  • public String substring(int beginIndex);

調(diào)用public String(char value[], int offset, int count);方法生成一個(gè)新的String實(shí)例

replace方法

  • public String replace(char oldChar, char newChar);
  • public String replace(CharSequence target, CharSequence replacement);
  • public String replaceAll(String regex, String replacement);
  • public String replaceFirst(String regex, String replacement);

1)replace的參數(shù)是char和CharSequence,即可以支持字符的替換,也支持字符串的替換 2)replaceAll和replaceFirst的參數(shù)是regex,即基于規(guī)則表達(dá)式的替換,比如,可以通過replaceAll(“\d”, “*”)把一個(gè)字符串所有的數(shù)字字符都換成星號(hào); 相同點(diǎn)是都是全部替換,即把源字符串中的某一字符或字符串全部換成指定的字符或字符串, 如果只想替換第一次出現(xiàn)的,可以使用 replaceFirst(),這個(gè)方法也是基于規(guī)則表達(dá)式的替換,但與replaceAll()不同的是,只替換第一次出現(xiàn)的字符串; 另外,如果replaceAll()和replaceFirst()所用的參數(shù)據(jù)不是基于規(guī)則表達(dá)式的,則與replace()替換字符串的效果是一樣的,即這兩者也支持字符串的操作;

codePointAt方法

public int codePointAt(int index);
public int codePointBefore(int index);
public int codePointCount(int beginIndex, int endIndex);
public int offsetByCodePoints(int index, int codePointOffset);
  • wiki

  • Code Point:A code point or code position is any of the numerical values that make up the code space.

  • String對(duì)象使用UTF-16表示Unicode字符,一般的符號(hào)只需要一個(gè)字符(兩個(gè)字節(jié))表示,但是一些符號(hào)需要兩個(gè)字符(四個(gè)字節(jié))表示,這種表示方法稱為Surrogate,第一個(gè)字符叫Surrogate High,第二個(gè)字符叫Surrogate Low。

  • Surrogate High的范圍是\uD800-\uDBFF,Surrogate Low的范圍是\uDC00-\uDFFF,在Unicode碼表中,\uD800-\uDFFF只用來表示Surrogate Pair,不代表實(shí)際符號(hào)。

    Unicode range D800–DFFF is used for surrogate pairs in UTF-16 (used by Windows) and CESU-8 transformation formats, allowing these encodings to represent the supplementary plane code points, whose values are too large to fit in 16 bits. A pair of 16-bit code points — the first from the high surrogate area (D800–DBFF), and the second from the low surrogate area (DC00–DFFF) — are combined to form a 32-bit code point from the supplementary planes. Unicode and ISO/IEC 10646 do not assign actual characters to any of the code points in the D800–DFFF range — these code points only have meaning when used in surrogate pairs. Hence an individual code point from a surrogate pair does not represent a character, is invalid unless used in a surrogate pair, and is
    unconditionally invalid in UTF-32 and UTF-8 (if strict conformance to the standard is applied).


public int codePointAt(int index);的作用是返回索引出字符的Code Point,如果此索引出的字符是Surrogate High,下一個(gè)索引的字符是Surrogate Low,則返回Surrogate Pair對(duì)應(yīng)的Code Point。

public static void main(String[] args)
{
    int uni = 0x1F691;
    String str = new String(Character.toChars(uni));
    System.out.println(str.codePointAt(0)); //輸出128657
}
  • 符號(hào)?? 的Unicode碼為U+1F691,對(duì)應(yīng)的十進(jìn)制數(shù)為128657,在String中需要兩個(gè)字符(Surrogate High和Surrogate Low)表示;
  • 使用codePointAt()可以讀取兩個(gè)字符組成的Surrogate Pair對(duì)應(yīng)的Code Point。

public int codePointCount(int beginIndex, int endIndex);計(jì)算字符串的Char[]從beginIndexendIndex-1之間Code Point的數(shù)目(Surrogate Pair算為一個(gè)),Unpaired surrogates算為一個(gè);

public static void main(String[] args)
{
    int uni = 0x1F691;
    String str = new String(Character.toChars(uni));
    System.out.println(str.codePointCount(0,1)); //輸出1
    System.out.println(str.length()); //輸出2
}
  • String.length()查詢的是字符數(shù)組的長度,由于U+1F691需要兩個(gè)字符表示,所有str.length() = 2;
  • codePointCount返回的是Code Point的個(gè)數(shù),由于字符串只有一個(gè)符號(hào)?? ,所有str.codePointCount(0,2)=1

public int codePointBefore(int index),如果字符數(shù)組中index-2的值是Surrogate High,index-1的值是Surrogate Low,則返回index-2和index-1組成的Surrogate Pair的Code Point,否則只返回index-1對(duì)應(yīng)的code point。

public static void main(String[] args)
{
    int uni = 0x1F691;
    String str = new String(Character.toChars(uni)) + "unicode";
    System.out.println(str.codePointBefore(2)); //輸出 128657
}
  • value[0]和value[1]可以組成Surrogate Pair,code point為128657

public int offsetByCodePoints(int index, int codePointOffset)方法返回String中從給定的index偏移codePointOfferSet個(gè)code points的索引

public static void main(String[] args)
{
    int uni = 0x1F691;
    String str = "uni" + new String(Character.toChars(uni)) + "code";
    System.out.println(str.offsetByCodePoints(0,4)); //輸出 5
}
  • 偏移4個(gè)code points后(uni占兩個(gè)字符,但是只有一個(gè)code point),所以偏移了5個(gè)字符,輸出結(jié)果為5.

concat()方法

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);
    }
  • 首先生成了一個(gè)字符數(shù)組buf[],將所有的字符放入新的字符數(shù)組;
  • 生產(chǎn)新的字符串,其中的value[]直接指向buf[];

indexOf()

public int indexOf(int ch);
public int indexOf(int ch, int fromIndex);
private int indexOfSupplementary(int ch, int fromIndex);//indexOf(int ch, int fromIndex)調(diào)用
public int indexOf(String str);
public int indexOf(String str, int fromIndex);
static int indexOf(char[] source, int sourceOffset, int sourceCount,
            char[] target, int targetOffset, int targetCount,
            int fromIndex);
  • indxeOf()作用是找出字符在字符串中第一次出現(xiàn)的位置;
  • 假設(shè)indexOf(int ch)indexOf(int ch, int fromIndex)的結(jié)果為k,如果ch > 0xFFFF,則codePointAt(K) = ch,否則charAt(K) = ch。

matches()方法

String.matches()方法匹配整個(gè)字符串是否符合正則表達(dá)式,不是匹配部分字符串

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 前言 最先接觸編程的知識(shí)是在大學(xué)里面,大學(xué)里面學(xué)了一些基礎(chǔ)的知識(shí),c語言,java語言,單片機(jī)的匯編語言等;大學(xué)畢...
    oceanfive閱讀 3,395評(píng)論 0 7
  • 從網(wǎng)上復(fù)制的,看別人的比較全面,自己搬過來,方便以后查找。原鏈接:https://www.cnblogs.com/...
    lxtyp閱讀 1,437評(píng)論 0 9
  • 一、Java 簡介 Java是由Sun Microsystems公司于1995年5月推出的Java面向?qū)ο蟪绦蛟O(shè)計(jì)...
    子非魚_t_閱讀 4,564評(píng)論 1 44
  • 成為伸手黨的一個(gè)非常根本的原因是,其實(shí)他還沒有養(yǎng)成獨(dú)立思考的習(xí)慣,心理依賴性極強(qiáng)。 比如群聊里面,總是有人會(huì)去問在...
    我是林路閱讀 280評(píng)論 0 1
  • 為了理解React的工作過程,我們就必須要了解React組件的生命周期,如同人有生老病死,每個(gè)組件在網(wǎng)頁中也會(huì)被創(chuàng)...
    蚊小文閱讀 310評(píng)論 0 0

友情鏈接更多精彩內(nèi)容