【问题标题】:Java - Public String(char[] value)Java - 公共字符串(字符 [] 值)
【发布时间】:2012-06-26 13:31:43
【问题描述】:

我的问题是:Public String(char[] value)。任何人都可以帮助我:它是否在每个 value[i] 内部循环。具体来说,

Public String(char[] value) 的意思是:

for each char[i]
returnedSTRING = returnedSTRING + char[i] 

还是不行?

【问题讨论】:

  • 将数组的内容复制到新构建的String的内部缓冲区中;这必然会涉及某个地方的循环......
  • @OliCharlesworth,应该是这样。然而,实际上我试图得到哪个更快,为什么?
  • what 和 what 之间哪一个?
  • @OliCharlesworth 它不需要循环,因为它调用 System.arraycopy 来完成繁重的工作,它一次只复制整个内存块;它不必遍历每个微小的元素
  • @AndreiBârsan:确实,但arrayCopy内部会有一个循环。

标签: java string


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    字符串对象在内部将所有字符串字符保存在char[] 数组中。这个构造函数只是将整个数组复制到内部表示。查看来源:

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

    【讨论】:

      【解决方案3】:

      来自文档:

      分配一个新的字符串,以便它表示当前包含在字符数组参数中的字符序列。字符数组的内容被复制;后续对字符数组的修改不会影响新创建的字符串。

      字符数组的内容被复制。 根据源代码,就像 mishadoff 指出的那样,使用了Arrays.copyOf(value, size)。然而,Arrays.copyOf(value, size) 反过来又调用System.arraycopy,这实际上并不迭代和分配,而是实际复制内存,类似于在 C/C++ 中调用memcpy() 所做的事情。这是由 Java 在内部完成的,因为它比普通循环快得多。 System.arraycopy 是一种本机方法,它利用了主机操作系统的内存管理功能。

      所以为了回答你的问题,字符不会在 for 中迭代,而是它们所在的整个内存块被 Java“批量”复制

      【讨论】:

        【解决方案4】:

        String class source code

        但是,根据 Java 的版本,它可能会有所不同。

        【讨论】:

          猜你喜欢
          • 2011-02-15
          • 1970-01-01
          • 1970-01-01
          • 2011-11-26
          • 2021-05-19
          • 2010-11-04
          • 2014-08-18
          • 2013-03-18
          • 2011-07-13
          相关资源
          最近更新 更多