• Post Reply Bookmark Topic Watch Topic
  • New Topic

difficulty getting object details back from hashmap  RSS feed

 
Dave Evans
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have got a hashmap created, and the method that creates it takes a reference number as the key, and then an object as the value.

The problem I'm having, is that when I try to get my object back out, all I get is myobjectname@235346 or some other memory address!

How can I turn this random string into something meaningful? I have about 4 values in that object which I want to be able to print to the screen. I've read through my text books about casting and stuff, but just can't seem to work this out, someone at least point me in the right direction?

Thanks,
Dave
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Dave,

Welcome to JavaRanch!

When you "print" a Java object -- using something like

System.out.println(theObject);

The println() method calls the object's toString() method, and displays that String. The default implementation of toString() -- which every class inherits by default, unless it overrides this implementation with one of its own -- returns a String that includes the class name, an "@" sign, and the return value of the object's hashCode() method -- i.e., what you're seeing. Your object's not lost: that's just what it looks like when you print your object.

Assuming your class is called MyClass, you need to say something like this:

MyClass theObject = (MyClass) myHashTable.get(theKey);

To get the data out of theObject, you should call its methods directly -- i.e., maybe something like

System.out.println(theObject.getValue1());

Alternatively, you could implement the toString() method in MyClass, and then just print the object, as before. Your toString() should return the String that you'd like to see when the object is printed.
 
Dave Evans
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Perfect answer, I have implemented this and my assignment is suddenly so much more simple! Please come and teach java at my university?!
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Dave Evans:
Please come and teach java at my university?!


Been there, done that, bought the T-shirt. But you're always welcome to come ask questions here at the Saloon!
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!