我的问题是关于:Public String(char[] value)。有人能帮我吗:它在内部是否为每个value[i]循环,或者不是。具体来说,Public String(char[] value)的意思是什么:
或者不?
for each char[i]
returnedSTRING = returnedSTRING + char[i]
或者不?
for each char[i]
returnedSTRING = returnedSTRING + char[i]
Java是开源的,如果你将源代码附加到Eclipse中,就可以使用F3查看函数。在这种情况下,String类具有以下构造函数,这正是你要找的:
/**
* Allocates a new {@code String} so that it represents the sequence of
* characters currently contained in the character array argument. The
* contents of the character array are copied; subsequent modification of
* the character array does not affect the newly created string.
*
* @param value
* The initial value of the string
*/
public String(char value[]) {
int size = value.length;
this.offset = 0;
this.count = size;
this.value = Arrays.copyOf(value, size);
}
编辑:如果你想知道的话,Arrays.copyOf 调用了 System.arraycopy。
字符串对象在内部使用char[]
数组保存所有字符串字符。此构造函数只是将整个数组复制到内部表示中。请参见源代码:
public String(char value[]) {
int size = value.length;
this.offset = 0;
this.count = size;
this.value = Arrays.copyOf(value, size);
}
根据文档:
分配一个新的字符串,使其表示字符数组参数中当前包含的字符序列。复制字符数组的内容;对字符数组的后续修改不会影响新创建的字符串。
复制字符数组的内容。
根据mishadoff指出的源代码,使用了Arrays.copyOf(value, size)
。然而,Arrays.copyOf(value, size)
又调用了System.arraycopy
,后者实际上并没有迭代和分配内存,而是像C/C++中的memcpy()
一样复制内存块。由于这比普通循环要快得多,Java内部执行此操作。 System.arraycopy
是一个本地方法,利用了主机操作系统的内存管理特性。
因此,回答您的问题,字符并没有被迭代处理,而是整个内存块被Java "批量"复制。