我试图理解如何java String实现.jdk7 source下面的代码显示了一个检查.originalValue.length > size我无法弄清楚它将如何实现/何时实现.我试图在一些java String创建语句中使用eclipse调试器,但这个检查从来都不是真的.是否有可能设计一个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;
}
...
}
Run Code Online (Sandbox Code Playgroud)
看一下这段代码:
String s1 = "123456789";
String s2 = new String(s1.substring(0, 2));
Run Code Online (Sandbox Code Playgroud)
第二个构造函数将匹配条件。诀窍在于子字符串方法。它不会创建真正的子字符串,而是复制底层数组并为其设置新的边界。构造新字符串的想法是制作字符串的副本,而不仅仅是分配相同的数组。这实际上就是为什么从大字符串中取出小子字符串可能会导致 OOM 异常。因为为了表示一小段信息,使用了大数组。