Tôi đã cố gắng hiểu cách java String
được triển khai. Mã số jdk7 source
bên dưới hiển thị séc cho originalValue.length > size
. Tôi không thể biết cách/khi nào nó thành sự thật. Tôi đã cố gắng sử dụng trình gỡ lỗi nhật thực trên một số chuỗi java câu lệnh tạo, nhưng kiểm tra này không bao giờ đúng. Có thể đưa ra một đối số String để kiểm tra này đúng không?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;
}
...
}
là s2.length> 3 ở đây? – Karthikeyan
Có, vì nó là cùng một mảng char bên dưới (không chỉ là một bằng nhau). – oddparity
Trong trường hợp này mảng s2 's underling sẽ có kích thước hai, không chín. – Mikhail