java - java 中的 toString 与 toString(参数) 与 valueOf(参数)

标签 java string casting tostring

我仍然很困惑这三种方法之间的确切区别是什么

例如:

Double d = 19.23456;
System.out.println(d.toString());
System.out.println(Double.toString(d));
System.out.println(String.valueOf(d));

以上所有方法都会打印值,但我想了解更多这些方法之间的逻辑含义和差异。哪种方法适合哪种场景?

我已经浏览了下面的链接,其中接受的答案指出 toString(parameter) 和 valueOf(parameter) 是相同的。那么toString呢?可能是我遗漏了重要的一点或其他东西。如果是这样,请将我的注意力转向它。

Integer.toString(int i) vs String.valueOf(int i)

我已经阅读了文档,但读完后我无法看出其中的差异。

根据官方文档:

toString

 Returns a string containing a concise, human-readable description of this object.
 Subclasses are encouraged to override this method and provide an implementation that takes into account the object's type and data. 
The default implementation is equivalent to the following expression: 

           getClass().getName() + '@' + Integer.toHexString(hashCode())

toString(参数)

Returns a string containing a concise, human-readable description of the specified double value

valueOf(参数)

Converts the specified object to its string representation. If the object is null return the string "null", otherwise use toString() to get the string representation.

提前谢谢

编辑:

嗯,我对 Eran 和 zapl 提供的答案都很满意。每个答案都从特定角度阐明了该方法的概念。为了接受答案,我会接受一个答案。谢谢您消除了我的疑虑。

最佳答案

Integer.toString()Integer.toString(int) 之间的区别在于后者是静态方法,因此可以为原始变量调用。前者是实例方法,只能在引用类型上调用。

String.valueOf(Object)toString() 实例方法不同,因为 String.valueOf(null) 将返回“null”,而 null.toString() 会抛出 NullPointerException。 当传递 null Integer 引用时,Integer.toString(int) 也会抛出 NullPointerException,因为尝试拆箱该 Integer 会导致该异常。

因此,如果您有一个 Integer i 变量,String.valueOf(i) 的行为将与 i.toString() 不同,并且Integer.toString(i)inull 时。

关于java - java 中的 toString 与 toString(参数) 与 valueOf(参数),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26930034/

相关文章:

sql - 带 array_to_string 的 Postgresql 请求

java - 如何比较字符串的百分比?

java - 提取的 pdf 文本未显示在控制台中

c - C 中不允许使用类型名称

java - 当通过服务名称从其他 docker-compose 服务请求时,Spring Boot REST 应用程序返回 400

java - 如何增加 'for-loop' 内的 char int 数组

c++ - 将 std::string 转义为 NSString*

c++ - 如何在 C++ 中读取字符串中以空格分隔的多个 double ?

java - log4j,嵌套诊断上下文

java - 调整 fragment 的尺寸