If I have an array of objects which have a toString method and I print the array using a for loop (e.g.: simply array[i]
to reach the objects and carry out System.out.println(array[i])
) will the toString method be invoked automatically? It seems to be but I just want to check this is what is going on.
问问题
71 次
2 回答
5
是的,它会的。
事实上,与隐式调用相比,这样做的好处.toString()
是可以在不引发异常的情况下处理空值。如果array[i]
是null
,then System.out.println(array[i])
将打印null
where System.out.println(array[i].toString())
will throw a NullPointerException
。
这是因为System.out.println(object)
方法调用System.out.print(object)
哪个调用String.valueOf(object)
哪个又调用object.toString()
。
于 2012-05-09T12:13:31.827 回答
1
于 2012-05-09T12:15:41.967 回答