[英]Is toString called for primitive types also?
I know that toString
is called in Java
whenever we print an object, and that is by default defined in Object
class which is superclass of all classes. 我知道每当我们打印一个对象时都会在Java
调用toString
,而这默认是在Object
类中定义的,它是所有类的超类。
But, my teachers says that toString
is also called when we print some primitive type
( int, char
etc). 但是,我的老师说当我们打印一些primitive type
( int, char
等)时也会调用toString
。
Is that true ? 真的吗 ?
Yes, but not in the sense that you would expect it to be. 是的,但不是你预期的那种意义。
System.out.println(someInt)
is just a wrapper for print
that also adds a line. 只是一个print
包装,也增加了一条线。
System.out.print(someInt)
String.valueOf(someInt)
Integer.toString(someInt)
which is a static method in the Integer class that returns a String
object representing the specified integer . 这是Integer类中的静态方法 ,它返回表示指定整数的String
对象 。 This method is not the same as Integer#toString()
, an instance method that transforms its Integer object into a string representing its int value. 这种方法是不一样的Integer#toString()
即其转换整数对象到表示其int值的字符串的实例方法。
someInt.toString()
won't work as someInt
does not extend Object
due to its not being an object. someInt.toString()
将无法工作,因为someInt
不会扩展Object
因为它不是一个对象。
Lets see how System.out.print(int)
works. 让我们看看System.out.print(int)
是如何工作的。 According to System
API System.out
is a PrintStream
: 根据System
API System.out
是一个PrintStream
:
public static final PrintStream out
In PrintStream
src we can see how it prints ints: 在PrintStream
src中我们可以看到它如何打印整数:
public void print(int i) {
write(String.valueOf(i));
}
And this is String.valueOf(int)
from String
src: 这是来自String
src的String.valueOf(int)
:
public static String valueOf(int i) {
return Integer.toString(i);
}
If you consider following code 如果您考虑以下代码
System.out.println(5);
Following thing will happen 以下事情将会发生
public void println(int x) {
synchronized (this) {
print(x);
newLine();
}
}
function from PrintStream
class will be called which internally will call print(x)
function as follows- 将调用PrintStream
类中的函数,该函数在内部将调用print(x)
函数,如下所示 -
public void print(int i) {
write(String.valueOf(i));
}
and now if you see valueOf() function in String class 现在如果你在String类中看到valueOf()函数
public static String valueOf(int i) {
return Integer.toString(i);
}
and 和
Integer.toString(i)
is what your teacher meant by calling toString() method. Integer.toString(i)
是你的老师通过调用toString()方法的意思。
The primitives are autoboxed to their respective object type. 原语被自动装箱到它们各自的对象类型。 So toString()
will call. 所以toString()
会调用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.