2013-08-17 36 views
5

我試圖瞭解如何實現一個java String。下面的代碼jdk7 source顯示檢查originalValue.length > size。我無法弄清楚它將如何/何時實現。我嘗試在一些java字符串上使用eclipse調試器創建語句,但這種檢查從來沒有真實。是否有可能設計一個字符串參數,這將使此檢查真實?java String構造函數邏輯

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

    /** The offset is the first index of the storage that is used. */ 
    private final int offset; 

    /** The count is the number of characters in the String. */ 
    private final int count; 

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

    /** 
    * Initializes a newly created {@code String} object so that it represents 
    * the same sequence of characters as the argument; in other words, the 
    * newly created string is a copy of the argument string. Unless an 
    * explicit copy of {@code original} is needed, use of this constructor is 
    * unnecessary since Strings are immutable. 
    * 
    * @param original 
    *   A {@code String} 
    */ 
    public String(String original) { 
     int size = original.count; 
     char[] originalValue = original.value; 
     char[] v; 
     if (originalValue.length > size) { 
      // The array representing the String is bigger than the new 
      // String itself. Perhaps this constructor is being called 
      // in order to trim the baggage, so make a copy of the array. 
      int off = original.offset; 
      v = Arrays.copyOfRange(originalValue, off, off+size); 
     } else { 
      // The array representing the String is the same 
      // size as the String, so no point in making a copy. 
      v = originalValue; 
     } 
     this.offset = 0; 
     this.count = size; 
     this.value = v; 
    } 
... 
} 

回答

3

看一看這段代碼:

String s1 = "123456789"; 
String s2 = new String(s1.substring(0, 2)); 

第二個構造函數將匹配狀態。技巧是在子串方法中。它並不構成真正的子字符串,而是複製底層數組,併爲其設置新的邊界。構建一個新字符串的想法是創建一個字符串的副本,而不僅僅是分配相同的數組。這實際上是爲什麼從一個大字符串中取出小字符串可能導致OOM異常。因爲代表了一大塊使用大數組的信息。

+0

是s2.length> 3在這裏? – Karthikeyan

+0

是的,因爲它是下面相同的字符數組(不只是一個相等的)。 – oddparity

+0

在這種情況下,s2的下屬陣列的尺寸是兩個,而不是九個。 – Mikhail

3

你可以調試這個。 Value代表底層char[]count代表view

String s = new String("Hello "); //value= [H, e, l, l, o, , , ] count=8 

String os = s.trim(); //value= [H, e, l, l, o, , , ] count=5