Stavo cercando di capire come è stato implementato uno java String
. Il codice jdk7 source
qui sotto mostra un controllo per originalValue.length > size
. Non riesco a capire come/quando avverrà. Ho provato a usare eclipse debugger su qualche stringa java dichiarazioni di creazione, ma questo controllo non è mai stato vero. È possibile escogitare un argomento String che renderebbe questo controllo vero?java String constructor logic
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 qui? – Karthikeyan
Sì, poiché è lo stesso array di char sotto (non solo uno uguale). – oddparity
In questo caso, l'array underender di s2 sarà di dimensione due, non nove. – Mikhail