Java-公共字符串(char[]值)
我的问题是关于:。有人能帮我吗:它是否对每个值[i]进行内部循环。具体来说, 公共字符串(char[]值)是否表示: 还是没有?请参见Java-公共字符串(char[]值),java,string,Java,String,我的问题是关于:。有人能帮我吗:它是否对每个值[i]进行内部循环。具体来说, 公共字符串(char[]值)是否表示: 还是没有?请参见 但是,根据Java版本的不同,它可能会有所不同。字符串对象在内部将所有字符串保存在char[]数组中。这个构造函数只是将整个数组复制到内部表示。见资料来源: public String(char value[]) { int size = value.length; this.offset = 0; this.co
但是,根据Java版本的不同,它可能会有所不同。字符串对象在内部将所有字符串保存在
char[]
数组中。这个构造函数只是将整个数组复制到内部表示。见资料来源:
public String(char value[]) {
int size = value.length;
this.offset = 0;
this.count = size;
this.value = Arrays.copyOf(value, size);
}
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);
}
编辑:如果您想知道,请致电 从文档中:
分配新字符串,使其表示当前包含在字符数组参数中的字符序列。复制字符数组的内容;随后对字符数组的修改不会影响新创建的字符串
将复制字符数组的内容。
根据源代码,就像mishadoff指出的那样,Arrays.copyOf(value,size)
被使用。然而,Arrays.copyOf(value,size)
依次调用System.arraycopy
,后者实际上并不迭代和分配内存,而是复制内存,这与在C/C++中调用memcpy()
类似。这是由Java内部完成的,因为它比普通循环快得多System.arraycopy
是一种本机方法,它利用了主机操作系统的内存管理功能
因此,为了回答您的问题,字符不是在for中迭代的,而是它们所在的整个内存块被Java“批量”复制它将数组的内容复制到新构造的字符串的内部缓冲区中;这必然会涉及到某个地方的循环…@OliCharlesworth,应该是这样。然而,实际上我试图知道哪一个更快,为什么更快?在什么和什么之间是哪一个?@OliCharlesworth它不需要循环,因为它调用System.arraycopy来完成繁重的工作,一次只复制整个内存块;它不必遍历每个微小的element@AndreiB–rsan:的确如此,但是在
arrayCopy
中会有一个循环。
/**
* 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);
}