字符串构造函数中怎么会发生'originalValue.length > size'?



下面是 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;
}

但是,我想知道怎么可能

if (originalValue.length > size)

发生?评论说"修剪行李"行李指的是什么?

看看子字符串,你会看到这是如何发生的。

String s1 = "Abcd"; String s2 = s1.substring(3)为例。这里的s1.size()是 1,但s1.value.length是 4。这是因为 s1.value 与 s2.value 相同。这是出于性能原因(子字符串在 O(1) 中运行,因为它不需要复制原始字符串的内容)。

使用子字符串可能会导致内存泄漏。假设你有一个很长的字符串,你只想保留它的一小部分。如果你只使用子字符串,你实际上会把原始字符串内容保留在内存中。执行String snippet = new String(reallyLongString.substring(x,y)) ,可防止浪费内存支持不再需要的大型字符数组。

参见 表达式"新字符串(...)"的目的是什么"在爪哇?以获取更多解释。

最新更新