gpt4 book ai didi

java - 在不创建新实例的情况下为 String 类赋值

转载 作者:行者123 更新时间:2023-11-30 07:12:43 24 4
gpt4 key购买 nike

如果这个问题已经被问过或者它太老了,请原谅。

字符串是一个类。我们可以在不创建新实例对象的情况下将值分配给 String。

比如 String someString = "Value";

如果不为 String 创建实例,这是如何工作的?是否可以创建用户定义的类来直接赋值而不创建新对象?

最佳答案

查看此 interesting article :

String is Really Special

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 has provided a special mechanism for keeping the String literals - in a so-called string common pool..

当你这样做时:

String myStr1 = "Hello";
String myStr2 = "Hello";

然后

myStr1 == myStr2 true,因为它们都存储在中(阅读文章)。

但是如果你构造一个新的String对象:

String myStr1 = new String("Hello");
String myStr2 = new String("Hello");

然后引用相等。

我强烈建议访问 JLS .它说 Strings 以不同的方式处理,就像那样:)

关于java - 在不创建新实例的情况下为 String 类赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20121524/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com