gpt4 book ai didi

java - 在字符串中使用 new 运算符创建两个对象有什么好处

转载 作者:行者123 更新时间:2023-11-30 08:17:11 25 4
gpt4 key购买 nike

在字符串中使用 new 运算符创建两个对象有什么好处。为什么创建两个对象以及它们的重要性是什么。

String s=new String("abc");

//creates two object

//why 2 object creation is required.

最佳答案

如果您执行以下测试:

String a = "foo";
String b = new String(a);
System.out.println(a == b);//returns false

所以这意味着ab不是同一个对象(这可能是强制性的,因为new使用运算符)。

如果您使用==来检查您是否正在谈论相同字符串(因此不是等效),这可能会很有用字符串)。

在这种情况下,这样做几乎没有什么用处,特别是因为 String 对象是不可变的,正如您可以在 manual 中读到的那样。 :

Initializes a newly created String object so that it represents the same sequence of characters as the argument; in other words, the newly created string is a copy of the argument string. Unless an explicit copy of original is needed, use of this constructor is unnecessary since Strings are immutable.

我认为唯一有用的情况是,如果您将某种“消息”方面附加到字符串,其中留言板仅接受不同的对象字符串。如果在这种情况下您想要插入同一消息两次,则需要复制 String

关于java - 在字符串中使用 new 运算符创建两个对象有什么好处,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29495298/

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