gpt4 book ai didi

java String构造函数逻辑

转载 作者:搜寻专家 更新时间:2023-10-31 19:55:55 25 4
gpt4 key购买 nike

我试图了解 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;
}
...
}

最佳答案

看看这段代码:

String s1 = "123456789";
String s2 = new String(s1.substring(0, 2));

第二个构造函数将匹配条件。诀窍在于 substring 方法。它不会生成真正的子字符串,而是复制底层数组并为其设置新的边界。构造新字符串的思想是复制一个字符串,而不是仅仅分配相同的数组。这就是为什么从大字符串中提取小子字符串可能会导致 OOM 异常的原因。因为用大数组来表示一小段信息。

关于java String构造函数逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18285654/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com