1

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.

4

2 回答 2

5

是的,它会的。

事实上,与隐式调用相比,这样做的好处.toString()是可以在不引发异常的情况下处理空值。如果array[i]nullthen System.out.println(array[i])将打印nullwhere 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

是的,它肯定会。

下面是一些关于工作方式println(Object)print(Object)方法的 API 描述。

println(对象)

打印(对象)

于 2012-05-09T12:15:41.967 回答