对string对象调用tostring()方法的效果

izj3ouym  于 2021-06-30  发布在  Java
关注(0)|答案(2)|浏览(301)

我的代码中有一个字符串对象

String tempString = "Some String";

如果我写些

tempString.toString();

这会在字符串池中创建另一个字符串对象吗?

at0kjp5o

at0kjp5o1#

不,因为 toString() 类中的方法 String 看起来像这样:

public String toString() {
    return this;
}
sczxawaw

sczxawaw2#

就像安德烈莫尼从密码里回答的那样。下面是javadoc的一部分
转换为字符串
公共字符串tostring()

This object (which is already a string!) is itself returned.

Specified by:
    toString in interface CharSequence
Overrides:
    toString in class Object

Returns:
    the string itself.

所以在这种情况下不会创建新对象。关于使用,这只是额外的一段代码,你正在添加,没有别的。
这方面的其他有趣读物
java:string的tostring()方法有什么实际用途吗?
如何在java中使用tostring方法?

相关问题