<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                合規國際互聯網加速 OSASE為企業客戶提供高速穩定SD-WAN國際加速解決方案。 廣告
                #String源碼分析 --- 從一段代碼說起: ``` public void stringTest(){ String a = "a"+"b"+1; String b = "ab1"; System.out.println(a == b); } ``` 大家猜一猜結果如何?如果你的結論是true。好吧,再來一段代碼: ``` public void stringTest(){ String a = new String("ab1"); String b = "ab1"; System.out.println(a == b); } ``` 結果如何呢?正確答案是false。 讓我們看看經過編譯器編譯后的代碼如何 ``` //第一段代碼 public void stringTest() { String a = "ab1"; String b = "ab1"; System.out.println(a == b); } ``` ``` //第二段代碼 public void stringTest() { String a1 = new String("ab1"); String b = "ab1"; System.out.println(a1 == b); } ``` 也就是說第一段代碼經過了編譯期優化,原因是編譯器發現"a"+"b"+1和"ab1"的效果是一樣的,都是不可變量組成。但是為什么他們的內存地址會相同呢?如果你對此還有興趣,那就一起看看String類的一些重要源碼吧。 一 String類 String類被final所修飾,也就是說String對象是不可變量,并發程序最喜歡不可變量了。String類實現了Serializable, Comparable<String>, CharSequence接口。 Comparable接口有compareTo(String s)方法,CharSequence接口有length(),charAt(int index),subSequence(int start,int end)方法。 二 String屬性 String類中包含一個不可變的char數組用來存放字符串,一個int型的變量hash用來存放計算后的哈希值。 ``` /** The value is used for character storage. */ private final char value[]; /** 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; ``` 三 String構造函數 ``` //不含參數的構造函數,一般沒什么用,因為value是不可變量 public String() { this.value = new char[0]; } //參數為String類型 public String(String original) { this.value = original.value; this.hash = original.hash; } //參數為char數組,使用java.utils包中的Arrays類復制 public String(char value[]) { this.value = Arrays.copyOf(value, value.length); } //從bytes數組中的offset位置開始,將長度為length的字節,以charsetName格式編碼,拷貝到value 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); } //調用public String(byte bytes[], int offset, int length, String charsetName)構造函數 public String(byte bytes[], String charsetName) throws UnsupportedEncodingException { this(bytes, 0, bytes.length, charsetName); } ``` 三 String常用方法 ``` boolean equals(Object anObject) public boolean equals(Object anObject) { //如果引用的是同一個對象,返回真 if (this == anObject) { return true; } //如果不是String類型的數據,返回假 if (anObject instanceof String) { String anotherString = (String) anObject; int n = value.length; //如果char數組長度不相等,返回假 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; } ``` equals方法經常用得到,它用來判斷兩個對象從實際意義上是否相等,String對象判斷規則: 內存地址相同,則為真。 如果對象類型不是String類型,則為假。否則繼續判斷。 如果對象長度不相等,則為假。否則繼續判斷。 從后往前,判斷String類中char數組value的單個字符是否相等,有不相等則為假。如果一直相等直到第一個數,則返回真。 由此可以看出,如果對兩個超長的字符串進行比較還是非常費時間的。 ``` int compareTo(String anotherString) public int compareTo(String anotherString) { //自身對象字符串長度len1 int len1 = value.length; //被比較對象字符串長度len2 int len2 = anotherString.value.length; //取兩個字符串長度的最小值lim int lim = Math.min(len1, len2); char v1[] = value; char v2[] = anotherString.value; int k = 0; //從value的第一個字符開始到最小長度lim處為止,如果字符不相等,返回自身(對象不相等處字符-被比較對象不相等字符) while (k < lim) { char c1 = v1[k]; char c2 = v2[k]; if (c1 != c2) { return c1 - c2; } k++; } //如果前面都相等,則返回(自身長度-被比較對象長度) return len1 - len2; } ``` 這個方法寫的很巧妙,先從0開始判斷字符大小。如果兩個對象能比較字符的地方比較完了還相等,就直接返回自身長度減被比較對象長度,如果兩個字符串長度相等,則返回的是0,巧妙地判斷了三種情況。 ``` int hashCode() public int hashCode() { int h = hash; //如果hash沒有被計算過,并且字符串不為空,則進行hashCode計算 if (h == 0 && value.length > 0) { char val[] = value; //計算過程 //s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1] for (int i = 0; i < value.length; i++) { h = 31 * h + val[i]; } //hash賦值 hash = h; } return h; } ``` String類重寫了hashCode方法,Object中的hashCode方法是一個Native調用。String類的hash采用多項式計算得來,我們完全可以通過不相同的字符串得出同樣的hash,所以兩個String對象的hashCode相同,并不代表兩個String是一樣的。 ``` boolean startsWith(String prefix,int toffset) 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. //如果起始地址小于0或者(起始地址+所比較對象長度)大于自身對象長度,返回假 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); } ``` 起始比較和末尾比較都是比較經常用得到的方法,例如在判斷一個字符串是不是http協議的,或者初步判斷一個文件是不是mp3文件,都可以采用這個方法進行比較。 ``` String concat(String str) 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); } ``` concat方法也是經常用的方法之一,它先判斷被添加字符串是否為空來決定要不要創建新的對象。 ``` String replace(char oldChar,char newChar) 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; } ``` 這個方法也有討巧的地方,例如最開始先找出舊值出現的位置,這樣節省了一部分對比的時間。replace(String oldStr,String newStr)方法通過正則表達式來判斷。 ``` String trim() public String trim() { int len = value.length; int st = 0; char[] val = value; /* avoid getfield opcode */ //找到字符串前段沒有空格的位置 while ((st < len) && (val[st] <= ' ')) { st++; } //找到字符串末尾沒有空格的位置 while ((st < len) && (val[len - 1] <= ' ')) { len--; } //如果前后都沒有出現空格,返回字符串本身 return ((st > 0) || (len < value.length)) ? substring(st, len) : this; } ``` trim方法用起來也6的飛起 ``` String intern() public native String intern(); ``` intern方法是Native調用,它的作用是在方法區中的常量池里通過equals方法尋找等值的對象,如果沒有找到則在常量池中開辟一片空間存放字符串并返回該對應String的引用,否則直接返回常量池中已存在String對象的引用。 將引言中第二段代碼 ``` //String a = new String("ab1"); //改為 String a = new String("ab1").intern(); ``` 則結果為為真,原因在于a所指向的地址來自于常量池,而b所指向的字符串常量默認會調用這個方法,所以a和b都指向了同一個地址空間。 ``` int hash32() private transient int hash32 = 0; int hash32() { int h = hash32; if (0 == h) { // harmless data race on hash32 here. h = sun.misc.Hashing.murmur3_32(HASHING_SEED, value, 0, value.length); // ensure result is not zero to avoid recalcing h = (0 != h) ? h : 1; hash32 = h; } return h; } ``` 在JDK1.7中,Hash相關集合類在String類作key的情況下,不再使用hashCode方式離散數據,而是采用hash32方法。這個方法默認使用系統當前時間,String類地址,System類地址等作為因子計算得到hash種子,通過hash種子在經過hash得到32位的int型數值。 ``` public int length() { return value.length; } public String toString() { return this; } public boolean isEmpty() { return value.length == 0; } public char charAt(int index) { if ((index < 0) || (index >= value.length)) { throw new StringIndexOutOfBoundsException(index); } return value[index]; } ``` 以上是一些簡單的常用方法。 總結 String對象是不可變類型,返回類型為String的String方法每次返回的都是新的String對象,除了某些方法的某些特定條件返回自身。 String對象的三種比較方式: ==內存比較:直接對比兩個引用所指向的內存值,精確簡潔直接明了。 equals字符串值比較:比較兩個引用所指對象字面值是否相等。 hashCode字符串數值化比較:將字符串數值化。兩個引用的hashCode相同,不保證內存一定相同,不保證字面值一定相同。
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看