This week's book giveaway is in the OCMJEA forum.
We're giving away four copies of OCM Java EE 6 Enterprise Architect Exam Guide and have Paul Allen & Joseph Bambara on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes How do I covert on object into string Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCM Java EE 6 Enterprise Architect Exam Guide this week in the OCMJEA forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "How do I covert on object into string" Watch "How do I covert on object into string" New topic
Author

How do I covert on object into string

Gopu Akraju
Ranch Hand

Joined: Jan 13, 2008
Posts: 242
I have a Map with object(class) as key and value pair.

I am trying to print them as follows:



Ann is a map as below:



Whne I try to print the key and value pair, using toString() {pairs.getKey().toString() and pairs.getValue().toString()}, I am not able to print them as it prints as below:


How do I convert the ojects into string to print? Thnaks.
Sagar Rohankar
Ranch Hand

Joined: Feb 19, 2008
Posts: 2902
    
    1

You need to override toString() method in your AnnType and Ann class, by default the Object#toString() method returns hash code !!
like this



[LEARNING bLOG] | [Freelance Web Designer] | [and "Rohan" is part of my surname]
Gopu Akraju
Ranch Hand

Joined: Jan 13, 2008
Posts: 242
Thanks Sagar.

I tried as below in both the classes:



But I still get the same output as I mentioned earlier.
Sagar Rohankar
Ranch Hand

Joined: Feb 19, 2008
Posts: 2902
    
    1

The main intention behind overriding Object#toString() , method in your class is to print some meaningful data , explaining your class ,

eg,
This may be the implementation of your Ann class


So whenever you print object , tou endup calling Ann#toString() method ;


And this code you implemented is the default code of Object#toString() method

Hope this clarifies
[ July 08, 2008: Message edited by: Sagar Rohankar ]
 
Don't get me started about those stupid light bulbs.
 
subject: How do I covert on object into string