怎么可能'originalValue.length> size'发生在String构造函数中? [英] how could 'originalValue.length > size' happen in the String constructor?

查看:124
本文介绍了怎么可能'originalValue.length> size'发生在String构造函数中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

但是,我想知道怎么可能

But, I wonder how could

if (originalValue.length > size)

发生?评论说'削减行李'行李指的是什么?

happen? The comment says 'trim the baggage', what does baggage refer to?

推荐答案

看看子字符串,你会看到这是怎么发生的。

Take a look at substring, and you'll see how this can happen.

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

Take for instance String s1 = "Abcd"; String s2 = s1.substring(3). Here s1.size() is 1, but s1.value.length is 4. This is because s1.value is the same as s2.value. This is done of performance reasons (substring is running in O(1), since it doesn't need to copy the content of the original String).

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

Using substring can lead to a memory leak. Say you have a really long String, and you only want to keep a small part of it. If you just use substring, you will actually keep the original string content in memory. Doing String snippet = new String(reallyLongString.substring(x,y)), prevents you from wasting memory backing a large char array no longer needed.

另见表达式new String(...)的目的是什么?在Java?中有更多解释。

这篇关于怎么可能'originalValue.length> size'发生在String构造函数中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆