我試圖瞭解如何實現一個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;
}
...
}
是s2.length> 3在這裏? – Karthikeyan
是的,因爲它是下面相同的字符數組(不只是一個相等的)。 – oddparity
在這種情況下,s2的下屬陣列的尺寸是兩個,而不是九個。 – Mikhail