天天看點

Java String源碼解析

String類概要

  • 所有的字元串字面量都屬于String類,String對象建立後不可改變,是以可以緩存共享,StringBuilder,StringBuffer是可變的實作
  • String類提供了操作字元序列中單個字元的方法,比如有比較字元串,搜尋字元串等
  • Java語言提供了對字元串連接配接運算符的特别支援(+),該符号也可用于将其他類型轉換成字元串。
  • 字元串的連接配接實際上是通過StringBuffer或者StringBuilder的append()方法來實作的
  • 一般情況下,傳遞一個空參數在這類構造函數或方法會導緻NullPointerException異常被抛出。
  • String表示一個字元串通過UTF-16(unicode)格式,補充字元通過代理對表示。索引值參考字元編碼單元,是以補充字元在String中占兩個位置。

String是不可變的

  • String是常量,一旦被建立就不可被改變,是以可以用來共享

從String的怪異現象講起

String是否相等

==判斷的是對象的記憶體起始位址是否相同,equals判斷自定義的語義是否相同

  • JVM為了提高記憶體效率,将所有不可變的字元串緩存在常量池中,當有新的不可變的字元串需要建立時,如果常量池中存在相等的字元串就直接将引用指向已有的字元串常量,而不會建立新對象
  • new建立的對象存儲在堆記憶體,不可能與常量區的對象具有相同位址
  • 直接用字面量初始化String要比用new 關鍵字建立String對象效率更高
public class Demo {
    public static void main(String[] args) throws Exception {
        String s = "abc";
        String s1 = "abc";
        String s2 = "a" + "bc";
        final String str1 = "a";
        final String str2 = "bc";
        String s3 = str1 + str2;
        String s4 = new String("abc");
        System.out.println(s == s1);
        System.out.println(s == s2);
        System.out.println(s == s3);
        System.out.println(s == s4);
    }
} //結果:true    true    true    false           

為什麼String不可變

final修飾變量,如果是基本類型那麼内容運作期間不可變,如果是引用類型那麼引用的對象(包括數組)運作期位址不可變,但是對象(數組)的内容是可以改變的

  • final隻是保證value不會指向其他的數組,但不保證數組内容不可修改
  • private屬性保證了不可以在類外通路數組,也就不能改變其内容
  • String内部沒有改變value内容的函數,是以String就不可變了
  • String聲明為final杜絕了通過繼承的方法添加新的函數
  • 基于數組的構造方法,會拷貝數組元素,進而避免了通過外部引用修改value的情況
  • 用String構造其他可變對象時,涉及的數組隻是傳回的數組的拷貝而不是原數組,例如 new StringBuilder(str),會把str數組進行拷貝後傳遞給StringBuilder而不是傳遞原數組

當然隻要類庫設計人願意,隻要增加一個類似的setCharAt(index)的接口,String就變成可變的了

private final char value[];
    private int hash; // Default to 0  
    public String(char value[]) {
        this.value = Arrays.copyOf(value, value.length);
    }             

通過反射改變String

  • final 隻在編譯器有效,在運作期間無效,是以可以通過反射改變value引用的對象
  • s與str始終具有相同的記憶體位址,反射改變了s的内容,并沒有新建立對象
  • s 與 s1對應常量池中的兩個對象,是以即便通過反射修改了s的内容,他們兩個的記憶體位址還是不同的
public class Demo {
    public static void main(String[] args) throws Exception {
        String s = "abc";
        String str = s;
        String s1 = "bbb";
        System.out.println(str == s);
        Field f = s.getClass().getDeclaredField("value");
        f.setAccessible(true);
        f.set(s, new char[]{'b', 'b', 'b'});
        System.out.println(str + "    " + s);
        System.out.println(s == str);
        System.out.println(s == s1);
    }
}  //結果:bbb    bbb    true    false           

String的HashCode

s的内容改變了但是hashCode值并沒有改變,雖然s與s1的内容是相同的但是他們hashCode值并不相同

  • Object的hashCode方法傳回的是16進制記憶體位址,String類重寫了hashCode的,hashCode值的計算是基于字元串内容的
  • String的hashCode值初始為0,由于String是不可變的,當第一次運作完hashCode方法後String類對HashCode值進行了緩存,下一次在調用時直接傳回hash值
public class Demo {
    public static void main(String[] args) throws Exception {
        String s = "abc";
        String s1 = "bbb";
        System.out.println(s.hashCode());
        Field f = s.getClass().getDeclaredField("value");
        f.setAccessible(true);
        f.set(s, new char[]{'b', 'b', 'b'});
        System.out.println(s + "    "+ s1);
        System.out.println(s.hashCode() +" " +s1.hashCode());
    }
}  //結果:96354    bbb    bbb    96354 97314           

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

toString方法中的this

  • Java為String類重載了“+”操作符,String類與其他類對象進行連接配接時會調用其他類的toString方法
  • 如果在其他類的toString方法中用“+”對this進行連接配接就會出現無限遞歸調用而出現棧溢出錯誤
  • 解決方法将this換做super.this
public class Demo {
    @Override
    public String toString() {
        //會造成遞歸調用
//        return "address"+super.toString();
        return "address"+super.toString();
    }
    public static void main(String[] args) {
        System.out.println(new Demo());
    }
}             

CodePoints與CodeUnit

String的length表示的是代碼單元的個數,而不是字元的個數

  • codePoints是代碼點, 表示的是例如’A’, ‘王’ 這種字元,每種字元都有一個唯一的數字編号,這個數字編号就叫unicode code point。目前code point的數值範圍是0~0x10FFFF。
  • codeUnit是代碼單元, 它根據編碼不同而不同, 可以了解為是字元編碼的基本單元,java中的char是兩個位元組, 也就是16位的。這樣也反映了一個char隻能表示從u+0000~u+FFFF範圍的unicode字元, 在這個範圍的字元也叫BMP(basic Multiligual Plane ), 超出這個範圍的叫增補字元,增補字元占用兩個代碼單元。
public class Demo {
    public static void main(String[] args) {
        String s = "\u1D56B";
        System.out.println(s);
        System.out.println(s.length());
    }
}             

我們看看String是怎麼處理增補字元的

  • 首先value字元數組的長度是根據代碼單元來定的,每出現一個Surrogate字元數組長度在count的基礎上加一
  • BMP字元直接存儲,增補字元的用兩個char分别存儲高位和低位
public String(int[] codePoints, int offset, int count) {
        if (offset < 0) {
            throw new StringIndexOutOfBoundsException(offset);
        }
        if (count < 0) {
            throw new StringIndexOutOfBoundsException(count);
        }
        // Note: offset or count might be near -1>>>1.
        if (offset > codePoints.length - count) {
            throw new StringIndexOutOfBoundsException(offset + count);
        }
        final int end = offset + count;
        // Pass 1: Compute precise size of char[]
        int n = count;
        for (int i = offset; i < end; i++) {
            int c = codePoints[i];
            if (Character.isBmpCodePoint(c))
                continue;
            else if (Character.isValidCodePoint(c))
                n++;
            else throw new IllegalArgumentException(Integer.toString(c));
        }
        // Pass 2: Allocate and fill in char[]
        final char[] v = new char[n];
        for (int i = offset, j = 0; i < end; i++, j++) {
            int c = codePoints[i];
            if (Character.isBmpCodePoint(c))
                v[j] = (char)c;
            else
                Character.toSurrogates(c, v, j++);
        }
        this.value = v;
    }  
    static void toSurrogates(int codePoint, char[] dst, int index) {
        // We write elements "backwards" to guarantee all-or-nothing
        dst[index+1] = lowSurrogate(codePoint);
        dst[index] = highSurrogate(codePoint);
    }             

源碼解析

聲明

  • String類可序列化,可比較,實作CharSequence接口提供了對字元的基本操作
  • String内部使用final字元數組進行存儲,涉及value數組的操作都使用了拷貝數組元素的方法,保證了不能在外部修改字元數組
  • String重寫了Object的hashCode函數使hash值基于字元數組内容,但是由于String緩存了hash值,是以即便通過反射改變了字元數組内容,hashhashCode傳回值不會自動更新
  • serialVersionUID 用來确定類的版本是否正确,如果不是同一個類會抛出InvalidCastException異常
public final class String
    implements java.io.Serializable, Comparable<String>, CharSequence { 
    private final char value[];
    private static final long serialVersionUID = -6849794470754667710L;  
    /** Cache the hash code for the string */
    private int hash; // Default to 0
    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;
    }             

構造函數

  • String主要提供了通過String,StringBuilder,StringBuffer,char數組,int數組(CodePoint),byte數組(需要指定編碼)進行初始化
  • 當通過字元串初始化字元串時,并沒有執行value數組拷貝,因為original的value數組是不可以在外部修改的,也就保證了新String對象的不可修改
  • 通過字元數組,StringBuffer,StringBuilder進行初始化時,就要執行value數組元素的拷貝,建立新數組,防止外部對value内容的改變
  • 通過byte數組進行初始化,需要指定編碼,或使用預設編碼(ISO-8859-1),否則無法正确解釋位元組内容
  • 通過Unicode代碼點進行的初始化,可能會包含非BMP字元(int值大于65535),這時候字元串的長度可能會長于int數組的長度,(見本文前面增補字元處理部分)
public String(String original) {
        this.value = original.value;
        this.hash = original.hash;
    }  
    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());
    }  
    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) {
            throw new StringIndexOutOfBoundsException(count);
        }
        // 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);
    } 
    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) {
        checkBounds(bytes, offset, length);
        this.value = StringCoding.decode(bytes, offset, length);
    }  
    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;
        }
    }            

内部構造函數

使用外部數組來初始化String内部數組隻有保證傳入的數組不可能被改變才能保證String的不可變性,例如用String初始化String對象時

  • 這種方法使用共享value數組的方法避免了數組的拷貝,提高了效率
  • 上面分析指出如果直接使用外部傳入的數組不能保證String的不可變性,這個方法隻在String的内部使用,不能由外部調用
  • 添加share參數,隻是為了重載構造函數,share必須為true
  • 該函數隻用在不能縮短String長度的函數中,如concat(str1,str2),如果用在縮短String長度的函數如subString中會造成記憶體洩漏
String(char[] value, boolean share) {
        // assert share : "unshared not supported";
        this.value = value;
    }  
    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);
    }  
        // 使用了Arrays.copyof方法來構造新的數組,拷貝元素,而不是共用數組
    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);
    }             

如果String(value,share)可以在外部使用,就可以改變字元串内容

public class Demo {
    public static void main(String[] args) {
        char[] arr = new char[] {'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd'};
        String s = new String(arr,true);
        arr[0] = 'a';
        System.out.println(s);
    }
}            

aLongString 已經不用了,但是由于其與aPart共享value數組,是以不能被回收,造成記憶體洩漏

public String subTest(){
        String aLongString = "...a very long string..."; 
        String aPart = aLongString.substring(20, 40);
        return aPart;
    }           

主要方法

其他主要方法

length() 傳回字元串長度

isEmpty() 傳回字元串是否為空

charAt(int index) 傳回字元串中第(index+1)個字元

char[] toCharArray() 轉化成字元數組

trim() 去掉兩端空格

toUpperCase() 轉化為大寫

toLowerCase() 轉化為小寫

String concat(String str) //拼接字元串

String replace(char oldChar, char newChar) //将字元串中的oldChar字元換成newChar字元

//以上兩個方法都使用了String(char[] value, boolean share);

boolean matches(String regex) //判斷字元串是否比對給定的regex正規表達式

boolean contains(CharSequence s) //判斷字元串是否包含字元序列s

String[] split(String regex, int limit) 按照字元regex将字元串分成limit份。

String[] split(String regex)
           

重載的valueOf方法

可以看到主要是調用構造函數或者是調用對應類型的toString完成到字元串的轉換

public static String valueOf(boolean b) {
        return b ? "true" : "false";
    }
    public static String valueOf(char c) {
        char data[] = {c};
        return new String(data, true);
    }
    public static String valueOf(int i) {
        return Integer.toString(i);
    }
    public static String valueOf(long l) {
        return Long.toString(l);
    }
    public static String valueOf(float f) {
        return Float.toString(f);
    }
    public static String valueOf(double d) {
        return Double.toString(d);
    }  
    public static String valueOf(char data[], int offset, int count) {
        return new String(data, offset, count);
    } 
    public static String copyValueOf(char data[], int offset, int count) {
        // All public String constructors now copy the data.
        return new String(data, offset, count);
    }            

字元串查找算法 indexOf

可以看到String的字元串比對算法使用的是樸素的比對算法,即前向比對,當遇到不比對字元時,主串從下一個字元開始,字串從開始位置開始

其他相關字元串比對算法
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;
    }             

編碼問題 getBytes

  • 字元串最終都是使用機器碼以位元組存儲的,當我們将字元串轉換為位元組的時候也需要給定編碼,同一個字元不同的編碼就對應不同的位元組
  • 如不指定編碼,就會使用預設的編碼ISO-8859-1進行編碼
  • 編碼時為了避免平台編碼的幹擾,應當指定确定的編碼
String s = "你好,世界!";
    byte[] bytes = s.getBytes("utf-8");  

    public byte[] getBytes(String charsetName)
            throws UnsupportedEncodingException {
        if (charsetName == null) throw new NullPointerException();
        return StringCoding.encode(charsetName, value, 0, value.length);
    } 
    static byte[] encode(String charsetName, char[] ca, int off, int len)
        throws UnsupportedEncodingException
    {
        StringEncoder se = deref(encoder);
        String csn = (charsetName == null) ? "ISO-8859-1" : charsetName;
        if ((se == null) || !(csn.equals(se.requestedCharsetName())
                              || csn.equals(se.charsetName()))) {
            se = null;
            try {
                Charset cs = lookupCharset(csn);
                if (cs != null)
                    se = new StringEncoder(cs, csn);
            } catch (IllegalCharsetNameException x) {}
            if (se == null)
                throw new UnsupportedEncodingException (csn);
            set(encoder, se);
        }
        return se.encode(ca, off, len);
    }            

比較方法

  • 所有比較方法都是比較對應的字元數組的内容,後兩個比較方法用來進行區段比較
  • 在進行數組比較時,如果可以通過長度進行初步判斷,一般可以提高效率
boolean equals(Object anObject);
    boolean contentEquals(StringBuffer sb);
    boolean contentEquals(CharSequence cs);
    boolean equalsIgnoreCase(String anotherString);
    int compareTo(String anotherString);
    int compareToIgnoreCase(String str);
    boolean regionMatches(int toffset, String other, int ooffset,int len)  //局部比對
    boolean regionMatches(boolean ignoreCase, int toffset,String other, int ooffset, int len)   //局部比對  

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

替換函數 replace

  • 單字元替換會替換所有特定字元的出現
  • replace為普通(literal)替換,不用正規表達式
  • replaceFirst與replaceAll都使用了正規表達式
public String replace(CharSequence target, CharSequence replacement) {
        return Pattern.compile(target.toString(), Pattern.LITERAL).matcher(
                this).replaceAll(Matcher.quoteReplacement(replacement.toString()));
    } 
    public String replaceFirst(String regex, String replacement) {
        return Pattern.compile(regex).matcher(this).replaceFirst(replacement);
    }
    public String replaceAll(String regex, String replacement) {
        return Pattern.compile(regex).matcher(this).replaceAll(replacement);
    } 
    public String replace(char oldChar, char newChar) {
        if (oldChar != newChar) {
            int len = value.length;
            int i = -1;
            char[] val = value; /* avoid getfield opcode */
            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) ? newChar : c;
                    i++;
                }
                return new String(buf, true);
            }
        }
        return this;
    }           

常量池相關方法

  • 每當定義一個字元串字面量,字面量進行字元串連接配接,或者final的String字面量初始化的變量的連接配接的變量時都會檢查常量池中是否有對應的字元串,如果有就不建立新的字元串,而是傳回指向常量池對應字元串的引用
  • 所有通過new String(str)方式建立的對象都會存在與堆區,而非常量區
  • 普通變量的連接配接,由于不能在編譯期确定下來,是以不會存儲在常量區
public native String intern();             

運算符的重載

  • String對“+”運算符進行了重載,通過反編譯我們看到重載是通過StringBuilder的append方法,及String的valueOf方法實作的
  • int值轉String過程中(”“+i)這種方法實際為(new StringBuilder()).append(i).toString();,而另外兩種都是調用Integer的靜态方法Integer.toString完成
// int轉String的方法比較
public class Demo {
    public static void main(String[] args) throws Exception {
        int i = 5;
        String i1 = "" + i;
        String i2 = String.valueOf(i);
        String i3 = Integer.toString(i);
    }
} 
// 原始代碼
public class Demo {
    public static void main(String[] args) throws Exception {
        String string="hollis";
        String string2 = string + "chuang";
    }
} 
//反編譯代碼
public class Demo {
    public static void main(String[] args) throws Exception {
        String string = "hollis";
        String string2 = (new StringBuilder(String.valueOf(string))).append("chuang").toString();
    }
}