这更清晰而不是怀疑。在下面的:通过System.out.println转换为Integer Wrapper类对象的int值?
int a = 10;
System.out.println(a);
我断定的是,变量“a”的基本类型int
首先被转换到Integer
包装类对象,然后toString
方法被调用为该Integer
对象返回的整数值的字符串形式到println
方法。我的理解是否正确?如果不是什么正确的解释?
这更清晰而不是怀疑。在下面的:通过System.out.println转换为Integer Wrapper类对象的int值?
int a = 10;
System.out.println(a);
我断定的是,变量“a”的基本类型int
首先被转换到Integer
包装类对象,然后toString
方法被调用为该Integer
对象返回的整数值的字符串形式到println
方法。我的理解是否正确?如果不是什么正确的解释?
不,我认为这不是你解释的方式。
System.out是PrintStream类(存在于java.io包中)的静态引用,它具有直接打印基元的方法!
如果你检查System.out
的类型,你会发现它是一个PrintStream
。 Read the docs.
报价:
public void println(int x)
Prints an integer and then terminate the line. This method behaves
as though it invokes print(int) and then println().
Parameters:
x - The int to be printed.
所以,不,不转化为Integer
完成。 int
准确地匹配上述方法的签名,以便调用该方法。内部发生的情况未指定,但可能直接调用Integer.toString()
,转换为Integer
。
准确地说,它实际上使用了String.valueOf(int)
方法。
这是源代码,从PrintStream
/**
* Prints the string representation of the int {@code i} followed by a newline.
*/
public void println(int i) {
println(String.valueOf(i));
}
Yup..thats正确的解释。我对重载的方法“public void println(Object x)”感到困惑,在这种情况下默认的toString被调用。 – Singularity 2014-12-01 19:51:39
@ user2580086当你想打印你自己的对象时,你完全正因为这个原因而重写'toString'。 – Maroun 2014-12-01 19:52:39