• Post Reply Bookmark Topic Watch Topic
  • New Topic

calling toString() on an array  RSS feed

 
Ranch Hand
Posts: 205
13
Notepad
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
According to the api, calling toString() on an Object returns
getClass().getName() + '@' + Integer.toHexString(hashCode())
Testing this


Works as expected. Would it work for any class, as long as toString() isn't overridden?

Yes, seems to:

What about an array?

In this case, we get

The hashcode of the array doesn't agree.
I could understand that if there were some intervening class in the array's inheritance tree, in which toString() were overridden, but there isn't. The showTree() method shows that Object[] is directly descendant from Object. Plus, the class of Object[], ie [Ljava.lang.Object; doesn't look like something I can look up in the api to see if it overrides toString().

How come toString() doesn't work as specified when invoked on an array?
 
Ranch Hand
Posts: 56
5
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In your example, toString() isn't being called on the array, it's being called on the first element within the array. Because printf takes vararg parameters, the last parameter is interpreted as an array containing the remaining parameters. So:



is really the same as:



See if you can explain the results of:



Maybe replace new Object() with string literals to see what's happening.
 
Rancher
Posts: 3742
16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Sresh Rangi wrote:In your example, toString() isn't being called on the array, it's being called on the first element within the array. Because printf takes vararg parameters, the last parameter is interpreted as an array containing the remaining parameters.


Well spotted Sresh . I could see it was printing the hashCode of an Object rather than the Object array, but i couldn't think why.

Richard, you can stop the Object array from being treated as var-args by adding a cast. Try

and see that the object class is now [Ljava.lang.Object; (an array of Objects) rather than java.lang.Object.

 
Richard Hayward
Ranch Hand
Posts: 205
13
Notepad
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sresh & Joanne, thanks for the explanation guys.
All clear now!
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!