简体   繁体   English

Java字符串构造函数优化

[英]Java String Constructor Optimization

Say I have a method: 说我有一个方法:

public String getString() {
    char[] array = new char[]{'a', 'b', 'c'};
    return new String(array);
}

Is the array still copied in the String constructor or is the Java compiler smart enough to recognize that the elements in the array cannot change so it can just reference the array? 数组是否仍然在String构造函数中复制,或者Java编译器是否足够智能,以识别数组中的元素不能更改,因此它只能引用数组?

Thanks 谢谢

Since the java String class is immutable the constructor must copy the array. 由于java String类是不可变的,因此构造函数必须复制该数组。

Otherwise someone can hold a reference to the array and modify it: 否则,有人可以持有对数组的引用并进行修改:

char[] array = new char[]{'a', 'b', 'c'};
String string = new String(array);

array[1] = 'd'; // array modification must NOT affect the string

See the source of java.lang.String : 查看java.lang.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[]) {
    this.value = Arrays.copyOf(value, value.length);
}

Edit : 编辑

See also the source of java.util.Arrays which calls System.arraycopy . 另请参阅调用System.arraycopyjava.util.Arrays的源代码。

The answer should be obvious: For String to remain immutable, it must defensively copy the array. 答案应该是显而易见的:要使String保持不变,它必须防御性地复制数组。

Consider this code: 考虑以下代码:

public String getString() {
    char[] array = new char[]{'a', 'b', 'c'};
    String s = new String(array); // abc
    array[0] = 'x';
    return s; // xbc 
}

If the array is not copied, the backing array will have leaked out, exposing the String to mutability. 如果复制数组,则支持数组将泄漏,从而使String暴露于可变性。

Look at this contructor too: 看看这个构造函数:

  153     public String(String original) {
  154         this.value = original`.value;
  155         this.hash = original.hash;
  156     }

This would be a string literal: 这将是一个字符串文字:

"abc"

Which is just a call to String(char[] value) with a, b, c passed in as elements of a char array. 这只是对String(char[] value)的调用,其中a,b,c作为char数组的元素传入。 In short, String x = "abc" is just syntactic sugar that compiler provides you to get around what you are doing above. 简而言之, String x = "abc"只是语法糖,编译器为您提供了解决上述操作的方法。

If you see the source code, you will get your answer. 如果您看到源代码,您将得到答案。 The input array is copied and not referenced. 输入数组被复制而不被引用。 Here is the source code: 这是源代码:

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

static char[] from(char[] value) {
    return Arrays.copyOf(value, value.length);
} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM