[英]StringBuilder constructor accepts a StringBuilder object - why?
The class StringBuilder
defines four constructors, and none of them accepts a StringBuilder
, yet the following compiles: StringBuilder
类定义了四个构造函数,它们都不接受StringBuilder
,但以下编译:
StringBuilder sb = new StringBuilder(new StringBuilder("Hello"));
Does this mean that the anonymous StringBuilder
object gets somehow converted to a String internally by the compiler? 这是否意味着编译器在内部以某种方式将匿名StringBuilder
对象转换为String?
A StringBuilder
is a CharSequence
(it implements that interface), and there is a constructor taking a CharSequence
. StringBuilder
是CharSequence
(它实现了该接口),并且有一个构造函数采用CharSequence
。 This is why the given code compiles: 这就是给定代码编译的原因:
StringBuilder sb = new StringBuilder(new StringBuilder("Hello"));
What this constructor does is simply initialize the new StringBuilder
with the content of the given CharSequence
. 这个构造函数的作用就是使用给定CharSequence
的内容初始化新的StringBuilder
。 The result will be the same as having 结果将与拥有相同
StringBuilder sb = new StringBuilder("Hello");
There is a constructor that takes in a CharSequence
which is an interface that is implemented by StringBuilder and by String (among other classes). 有一个构造函数接受一个CharSequence
,它是一个由StringBuilder和String(以及其他类)实现的接口。
http://docs.oracle.com/javase/8/docs/api/java/lang/CharSequence.html http://docs.oracle.com/javase/8/docs/api/java/lang/CharSequence.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.