2013-08-17 12 views
5

はチェックを示しこのチェックは真実ではありませんでした。このチェックを真にするString引数を考案することは可能でしょうか?Java文字列コンストラクタロジック

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'の基底配列のサイズは9でなく2です。 – Mikhail

3

これをデバッグできます。 Valueは、基礎となるchar[]を表します。 countview

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