gpt4 book ai didi

java - 如何看懂java String源码

转载 作者:行者123 更新时间:2023-11-29 03:11:13 24 4
gpt4 key购买 nike

它是如何工作的?我不明白它是如何发展到这样的地步的,每当你改变原始字符串中的某些内容时,每次都会创建一个新字符串。 offset、value、count分别代表什么?

private final char value[];  
private final int offset;
private final int count;

public String() {
this.offset = 0;
this.count = 0;
this.value = new char[0];
}

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;
}

public String(char value[]) {
int size = value.length;
this.offset = 0;
this.count = size;
this.value = Arrays.copyOf(value, size);
}

public String(char value[], int offset, int count) {
if (offset < 0) {
throw new StringIndexOutOfBoundsException(offset);
}
if (count < 0) {
throw new StringIndexOutOfBoundsException(count);
}
// Note: offset or count might be near -1>>>1.
if (offset > value.length - count) {
throw new StringIndexOutOfBoundsException(offset + count);
}
this.offset = 0;
this.count = count;
this.value = Arrays.copyOfRange(value, offset, offset+count);
}

public String substring(int beginIndex, int endIndex) {
if (beginIndex < 0) {
throw new StringIndexOutOfBoundsException(beginIndex);
}
if (endIndex > count) {
throw new StringIndexOutOfBoundsException(endIndex);
}
if (beginIndex > endIndex) {
throw new StringIndexOutOfBoundsException(endIndex - beginIndex);
}
return ((beginIndex == 0) && (endIndex == count)) ? this :
new String(offset + beginIndex, endIndex - beginIndex, value);
}

public String concat(String str) {
int otherLen = str.length();
if (otherLen == 0) {
return this;
}
char buf[] = new char[count + otherLen];
getChars(0, count, buf, 0);
str.getChars(0, otherLen, buf, count);
return new String(0, count + otherLen, buf);
}

public static String valueOf(char data[]) {
return new String(data);
}

public static String valueOf(char c) {
char data[] = {c};
return new String(0, 1, data);
}

最佳答案

该值是字符串的底层字符数组。偏移量是字符串开始的位置,计数是它的长度。一个字符串可能在数组 {'a','b','c','d','e'} 中,计数为 3,偏移量为 1,它是 "bcd"。这样就不会为每个子字符串操作复制数组。

关于java - 如何看懂java String源码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29265620/

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