StringBuilder sb = "asd";
在Java中,这种说法显然是错误的。像 eclipse 这样的 IDE 会告诉你:
cannot convert from String to StringBuilder
但是,String
对象可以由 =
运算符初始化。
我想知道一些与内存分配相关的原因。
最佳答案
因为 StringBuilder
是一个对象,它需要被构造。您收到错误是因为 String 不是 StringBuilder
。
String比较特殊,它被设计为介于primitive和class1之间。您可以将字符串文字直接分配给 String 变量,而不是调用构造函数来创建 String 实例。
The designers of Java decided to retain primitive types in an object-oriented language, instead of making everything an object, so as to improve the performance of the language. Primitives are stored in the call stack, which require less storage spaces and are cheaper to manipulate. On the other hand, objects are stored in the program heap, which require complex memory management and more storage spaces.
For performance reason, Java's String is designed to be in between a primitive and a class.
更多阅读:
关于java - 为什么不能用一个String来初始化一个StringBuilder对象呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21159711/