File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Reading objects from a TreeMap Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Reading objects from a TreeMap" Watch "Reading objects from a TreeMap" New topic

Reading objects from a TreeMap

Shanna Ripley

Joined: Mar 12, 2010
Posts: 18
Hi All,

I have stored several objects of type CD (represents details of CD to be stored in a catalogue) into a TreeMap and am trying to retrieve the contents but having trouble.
Example of the code I'm using to populate the TreeMap....

I've tried the following code to print out the details...

This is the output I get...

Michael Jackson: [CD@164f1d0d, CD@23fc4bec, CD@8dc8569]

I guess it's having problems printing out the values of the CD object. Can anyone point me in the right direction of how to do this...I want the details of the CD object also printed out.

Thanks in advance.
Paul Clapham

Joined: Oct 14, 2005
Posts: 19973

Then all you have to do is to modify the CD class so that it has a method whose signature is

and put some code in that method which returns whatever you want to see instead of the default value for toString() -- which is what you're seeing there.

(By the way this has nothing to do with the fact that you put references to CD objects into a TreeMap.)
Shanna Ripley

Joined: Mar 12, 2010
Posts: 18
Thanks Paul for your reply.

I'm still new to this so having a few problems. So I have the toString() method you suggested in the CD class, how do I call that from the code I showed previously. I'm assuming it needs to be called on a CD object.

Thanks for your help
vibhor sharma

Joined: Dec 10, 2010
Posts: 19

public String toString() , method is available at java.lang.Object class , it returns the String representation of the Object.
normally when you write System.out.Print(SomeObjectRefernce), toSting() method of Object class gets called automatically.
Campbell Ritchie

Joined: Oct 13, 2005
Posts: 46375
The full details are in the documentation. If you look up System.out, you find this link and it tells you to look for another method!
I agree. Here's the link:
subject: Reading objects from a TreeMap
It's not a secret anymore!