gpt4 book ai didi

java - Java 中字符串的 'new' 运算符有什么用?

转载 作者:行者123 更新时间:2023-12-02 18:17:42 25 4
gpt4 key购买 nike

我有一个关于在 java 语句中使用 new 的非常基本的问题。例如,最后的 return 子句使用 new 来表示 String。为什么这里需要创建String?在什么情况下人们会选择使用new

public class A extends java.lang.Object {

public int number;

public String toString() {

return new String("Value : " + number);

}
}

最佳答案

在任何情况下,由于 String 是不可变的,因此显式创建字符串副本是没有意义的,除非您确实需要来自 Javadoc 的关于 constructor 的副本。 :

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.

表达式"Value : "+ number 已计算为新的String,因此返回 new String("Value : "+ number)相当于

String tmp = "Value : " + number;
return new String(tmp);

您可以看到它创建了一个无用的副本。

关于java - Java 中字符串的 'new' 运算符有什么用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28576058/

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