简体   繁体   English

Java String转换为char数组

[英]Java String transform to char array

I want to ask how does the "".value transform char array ,Thanks 我想问一下"".value如何转换char array ,谢谢

public final class String
implements java.io.Serializable, Comparable<String>, CharSequence {
/** The value is used for character storage. */
private final char value[];

/**
 * Initializes a newly created {@code String} object so that it represents
 * an empty character sequence.  Note that use of this constructor is
 * unnecessary since Strings are immutable.
 */
public String() {
    this.value = "".value;
}

You should tell, which JRE implementation you are looking at, when you cite its source code. 引用其源代码时,应该告诉您正在查看的是哪种JRE实现。

However, the code is quite simple: 但是,代码非常简单:

  • "" refers to a String constant which is initialized by the JVM ""是指由JVM初始化的String常量
  • since you are inside the String() constructor which may get called by application code, but not JVM internal initialization, it may safely refer to the "" constant 由于您位于String()构造函数中,因此可以由应用程序代码调用,但不能在JVM内部初始化中调用它,因此可以安全地引用""常量
  • like any other String object, it has the value field, so inside the String constructor, it is no problem to access that private field and copy the reference; 像其他任何String对象一样,它具有value字段,因此在String构造函数内部,访问该private字段并复制引用是没有问题的; it is equivalent to 它等效于

     String tmp = ""; this.value = tmp.value; 

Since both, the "" constant and the instance created with the String() constructor represent empty strings, there is no problem in sharing the char[] array instance between them. 由于""常量和使用String()构造函数创建的实例均表示空字符串,因此在它们之间共享char[]数组实例没有问题。 However, there are reasons against it: 但是,有一些反对的理由:

  • it is optimizing an uncommon case, as there is usually no reason to ever use the String() constructor at all 它正在优化一个不常见的情况,因为通常根本没有理由使用String()构造函数
  • it is fragile as it relies on a particular JVM behavior, ie that the constant "" is not constructed via the String() constructor; 它很脆弱,因为它依赖于特定的JVM行为,即,常量"" 不是通过String()构造函数构造的; if that assumption is wrong, this implementation will create a circular dependency 如果该假设是错误的,则此实现将创建循环依赖项
"".value 

创建空的char[]数组,等效于this.value = new char[0];

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

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